微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Pyplot:在辅助y轴上绘图时的单个图例

我有以下代码来绘制Pandas DataFrame的数据:

df = pd.read_csv('data.csv')

plt.figure()
plt.title('Title')

ax1 = df.R.plot(style='b', label='Suc. Rate')
ax1.set_ylabel('Success Rate / Coherence')

ax2 = df.C.plot(style='r', label='Coherence')

ax3 = df.S.plot(secondary_y=True, style='g', label='Size')
ax3.set_ylabel('Lexicon Size')

plt.legend()

这些图是正确的,但只有标签尺寸的最后一行显示在图例中.如何在一个图例中获得所有3行?

解决方法:

您需要从每个轴获取图例句柄和标签,然后将所有句柄和标签的列表传递给图例.您可以使用ax.get_legend_handles_labels()执行此操作:

import matplotlib.pyplot as plt
import pandas as pd

# Some sample data
df = pd.DataFrame({'C' : [4,5,6,7], 'S' : [10,20,30,40],'R' : [100,50,-30,-50]})

fig=plt.figure()
plt.title('Title')

ax1 = df.R.plot(style='b', label='Suc. Rate')
ax1.set_ylabel('Success Rate / Coherence')

ax2 = df.C.plot(style='r', label='Coherence')

ax3 = df.S.plot(secondary_y=True, style='g', label='Size')
ax3.set_ylabel('Lexicon Size')

handles,labels = [],[]
for ax in fig.axes:
    for h,l in zip(*ax.get_legend_handles_labels()):
        handles.append(h)
        labels.append(l)

plt.legend(handles,labels)

plt.show()

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐