gpt4 book ai didi

python - 绘图 : single legend when plotting on secondary y-axis

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:46 25 4
gpt4 key购买 nike

我有以下代码来绘制 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()

绘图是正确的,但图例中只显示了带有标签 Size 的最后一行。我怎样才能在一个图例中获得所有 3 行?

最佳答案

您需要从每个 Axes 获取图例 handleslabels,然后将所有图例和标签的列表传递给图例。您可以使用 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

关于python - 绘图 : single legend when plotting on secondary y-axis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com