python - 绘制数据框然后添加垂直线;如何为所有人获取自定义图例文本?

标签 python pandas matplotlib

我可以绘制一个数据框(2 个“Y”值)并向图中添加垂直线 (2),我可以为 Y 值或垂直线指定自定义图例文本,但不能同时为两者指定.

import pandas as pd
import matplotlib.pyplot as plt

d = {'x' : [1., 2., 3., 4.], 'y1' : [8., 6., 4., 2.], 'y2' : [-4., 13., 2.2, -1.1]}
df = pd.DataFrame(d)
ax = df.plot(x='x', y=['y1'], linestyle='-', color='b')
df.plot(x='x', y=['y2'], linestyle='--', color='y', ax=ax)
ax.legend(labels=['y1custom', 'y2custom'])
plt.axvline(x=1.5, color='r', linestyle='--', label='vline1.5custom')
plt.axvline(x=3.5, color='k', linestyle='--', label='vline3.5custom')
plt.legend()        # <---- comment out....or not....for different effects
plt.show()

代码中的关键行是“plt.legend()”。在代码中有了它,我得到了这个(注意图例有数据框列标签“y1”和“y2”而不是我想要的自定义标签):

with plt.legend() call

删除“plt.legend()”后,我得到了这个(图例只有数据框值的自定义标签,垂直线的图例甚至没有出现!):

without plt.legend() call

我怎样才能两全其美,特别是以下(无论顺序如何)我的传奇?:

y1custom
y2custom
vline1.5custom
vline3.5custom

当然我可以先重命名数据框的列,但是......呃!一定有更好的方法。

最佳答案

每次调用 legend() 都会覆盖最初创建的图例。因此,您需要创建一个包含所有所需标签的图例。

这意味着您可以通过 ax.get_legend_handles_labels() 获取当前标签,并将您不喜欢的标签替换为其他标签。然后在调用 legend() 时指定新的标签列表。

import pandas as pd
import matplotlib.pyplot as plt

d = {'x' : [1., 2., 3., 4.], 'y1' : [8., 6., 4., 2.], 'y2' : [-4., 13., 2.2, -1.1]}
df = pd.DataFrame(d)
ax = df.plot(x='x', y=['y1'], linestyle='-', color='b')
df.plot(x='x', y=['y2'], linestyle='--', color='y', ax=ax)

ax.axvline(x=1.5, color='r', linestyle='--', label='vline1.5custom')
ax.axvline(x=3.5, color='k', linestyle='--', label='vline3.5custom')

h,labels = ax.get_legend_handles_labels()
labels[:2] = ['y1custom','y2custom']
ax.legend(labels=labels)

plt.show()

enter image description here

关于python - 绘制数据框然后添加垂直线;如何为所有人获取自定义图例文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302095/

相关文章:

python - 如果装饰器更改了 API,我应该如何处理装饰函数的文档字符串?

python - Lassocv 的嵌套交叉验证

python - matplotlib 中的自定义标记

python - Pandas 中的十进制四舍五入

python - 修改 pandas 条形图的图例

python - 如何设置饼图 matplotlib 的透明度和背景颜色

python - Pandas 日期时间 : Calculate Number of Weeks Between Dates in Two Columns

python - 同时打印 x 次 - Python

python - pandas 在包含数字和字符串的列中应用小数

pandas - 如何分解具有相同值的多个数据框列?