MoChen
MoChen

Reputation: 317

Using Pandas DF and Matplotlib to plot primary(bar) and secondary(line) axis but legends to be shown together..?

Plots made with two legends one legend for bar chart on primary axis and the other one is for line chart on secondry axis, How to combine both the legends together.?? and save the plot to be used in a Power point

Below are my codes which is placing the legend to two locations but I want them to be combined one below the other.

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.legend('LegendB',loc=1)

This generates the plot but the Legend B is placed at the upper right hand side corner and Legend A is by default placed at the left hand upper corner. Also I could see that Legend B is cut and not showing all the characters.

When I changed the ax2.legend line as

ax2.legend('Legend B',loc=0)

Then both the legend superimpose on each other.Quite a mess actually.

For saving the figure I am using the code as

ax2.legend('LegendB',loc=1)    
fig = ax.get_figure()
fig.set_size_inches(9.5, 3)
fig.savefig('test.png', bbox_inches='tight',dpi=100)
plt.show() ## To Show the Plot

But this saves the figure with legend superimposed on each other at LOC=1

So my questions are : 1. How to combine the legends one below the other..?? 2. Ho to save it as it is showing the plot..??

Thanks Guys

Upvotes: 1

Views: 641

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40747

You can combine legends from multiple axes, but you need to do it (semi)manually. There are a few traps that you need to be aware here, since you are mixing pandas plot, and matplotlib plot. See matplotlib's legend guide for more details.

here is what I would write:

ax1 = df.plot(x=['TIME'], y=['Column A'], kind='bar', color='r', legend=False)
ax1.set_ylabel("Label A")
ax2 = ax1.twinx()
ax2.plot(df['Column B'].values, linestyle='-', marker='o', linewidth=2.0, color ='b', label="test2")
ax2.set_ylabel("Label B")

lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines1 + lines2, labels1 + labels2, loc=0)

Notice that I added a label parameter to ax2.plot. This is important to make sure the handle for the line will be returned by ax2.get_legend_handles_labels(). Pandas' plot automatically adds a label, so nothing to do there.

Notice also that I passed legend=False to pandas plot function to suppress the automatic creation of the first legend.

Upvotes: 0

Related Questions