Pyplot:在二次y轴上绘图时的单个图例。

时间:2020-12-04 23:41:51

I have the following code to plot the data of a 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()

The plots are correct, but only the last line with label Size is shown in the legend. How can I get all 3 lines in a single legend?

情节是正确的,但只有最后一行的标签尺寸显示在图例中。我怎么能在一个传说中得到这三条线?

1 个解决方案

#1


4  

You need to get the legend handles and labels from each Axes, and then pass lists of all the handles and labels to legends. You can use ax.get_legend_handles_labels() to do this:

您需要从每个坐标轴上获取传奇句柄和标签,然后将所有的句柄和标签的列表传递给传奇。您可以使用ax.get_legend_handles_label()来执行以下操作:

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()

Pyplot:在二次y轴上绘图时的单个图例。

#1


4  

You need to get the legend handles and labels from each Axes, and then pass lists of all the handles and labels to legends. You can use ax.get_legend_handles_labels() to do this:

您需要从每个坐标轴上获取传奇句柄和标签,然后将所有的句柄和标签的列表传递给传奇。您可以使用ax.get_legend_handles_label()来执行以下操作:

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()

Pyplot:在二次y轴上绘图时的单个图例。