使用辅助Y轴绘制带有Pandas数据框的条形图和折线图并将图例添加到一起

时间:2015-08-30 08:36:57

标签: python pandas matplotlib

我创建了一个绘图,其中我在主Y轴上有一个条形图,在辅助Y轴上使用Pandas数据框绘制折线图.X轴很常见,因此使用了twinx方法。

这是我使用的代码

ax = df.plot(x=['TIME'],y =['Column A'],kind='bar',use_index=True,color='g',legend=True)
ax.set_ylabel("Label A")

ax2 = ax.twinx()

ax2.plot(df[['Column B']].values,linestyle='-', marker='o', linewidth=2.0,color ='b')
ax2.set_ylabel("Label B")

这会创建所需的图表,但仅显示主要图例。我尝试将ax2.plot行更改为

ax2.plot(df[['Column B']].values,linestyle='-', marker='o', linewidth=2.0,color ='b',legend=True)

但这给了我一个错误" TypeError:没有行属性" legend""你们可以调查它们如何展示属于这两个属性的组合传说。

非常感谢。 莫晨

1 个答案:

答案 0 :(得分:0)

您可以使用legend方法处理每个轴的图例,例如

ax.legend('A', loc=1)

# ....

ax2.legend('B', loc=2)

以下是matplotlibhttp://matplotlib.org/users/legend_guide.html

中的图例指南