尝试理解使用pandas和matplotlib.pyplot时图例标签的顺序

e0bqpujr  于 2023-04-04  发布在  其他
关注(0)|答案(1)|浏览(121)

我试图理解为什么标签的顺序在下面的情况下会这样。
我首先绘制pandas数据框,然后绘制一条水平线。然后我更改图例标签并按顺序创建它们(pandas列名,行标签即['case0', 'case1', 'case2'] + ['line label'])。为什么最终结果改变了?
获得正确顺序的唯一方法是使用ax.legend(['line label']+['case0', 'case1', 'case2'], fontsize=6, loc='upper left'),但这是违反直觉的。

import numpy as np, pandas as pd

data = np.random.rand(5,3)

plt.figure(figsize=figsize, dpi=120)
ax=pd.DataFrame(data).plot.bar(color=pal)
ax.axhline(y=0.4, lw=1, ls='--', c='k', label='line')
ax.legend(['case0', 'case1', 'case2'] + ['line label'], fontsize=6, loc='upper left')

jum4pzuy

jum4pzuy1#

我做了一些研究,默认情况下,lines s被附加到图形之前的句柄:

data = np.random.rand(5,3)

ax=pd.DataFrame(data).plot.bar()
ax.axhline(y=0.4, lw=1, ls='--', c='k', label='line')

#added some new graph for testing
pd.DataFrame(data).plot.area(ax=ax)

#https://stackoverflow.com/a/53519547/2901002
handles, _ = ax.get_legend_handles_labels()
print (handles)
[<matplotlib.lines.Line2D object at 0x00000000116E5E50>, 
  <matplotlib.collections.PolyCollection object at 0x00000000117420D0>,
  <matplotlib.collections.PolyCollection object at 0x0000000011742430>, 
  <matplotlib.collections.PolyCollection object at 0x0000000011732CD0>, 
  <BarContainer object of 5 artists>,
  <BarContainer object of 5 artists>,
  <BarContainer object of 5 artists>]

可能的解决方案是append句柄到现有句柄的末尾:

data = np.random.rand(5,3)

# plt.figure(figsize=figsize, dpi=120)
ax=pd.DataFrame(data).plot.bar()

handles, _ = ax.get_legend_handles_labels()

#https://stackoverflow.com/questions/53516413/add-axhline-to-legend#comment115315673_53519547
handles.append(ax.axhline(y=0.4, lw=1, ls='--', c='k', label='line'))
print (handles)
[<BarContainer object of 5 artists>,
 <BarContainer object of 5 artists>, 
 <BarContainer object of 5 artists>, 
 <matplotlib.lines.Line2D object at 0x0000000011B39850>]
 
labels = ['case0', 'case1', 'case2'] + ['line label']
ax.legend(handles = handles, labels = labels)

相关问题