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

JNe*_*ens 3 python matplotlib legend pandas

我有以下代码来绘制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()
Run Code Online (Sandbox Code Playgroud)

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

tmd*_*son 6

你需要得到传说handles和labels从每个Axes,然后通过所有手柄的名单和标签的传说.你可以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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述