Plotting Bar and Line charts with Pandas data frame using secondary Y axis and adding the legend together

I created a plot in which I have a bar chart on primary Y axis and a line chart on a secondary Y axis using the Pandas dataframe.The X axis is common so used twinx method.

This is the code I used

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

This creates the desired chart but shows only the primary legend. I tried changing the ax2.plot lines as

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

But this gives me an error as “TypeError: There is no line property “legend”” could you guys please look into it as how to show the combined legends belonging to both the attributes.

Many Thanks.
MO Chen


Source: python

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.