Pandas Plot Multiple Series But Only Showing Legend For One Series
I'm using an ipython notebook (python 2) and am plotting both a barchart and a line plot on the same plot. There are two series (NPS and Count Ratings). However, when I try to dis
Solution 1:
The following code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame({"x" : np.arange(5),
"a" : np.exp(np.linspace(3,5,5)),
"b" : np.exp(-np.linspace(-1,0.5,5)**2)})
ax=df.plot(x="x", y="a", kind='line',color='green',label='NPS')
plt.ylabel('Net Promoter Score')
ax2 = df.plot(x="x", y="b", kind='bar',secondary_y=True,label='Count of Ratings', ax=ax)
plt.ylabel('Count Ratings')
plt.title('Superlongtitle that is not needed')
plt.show()
produces
Note that the first axes is given as argument to the second pandas plot (ax=ax
) and no legend is added via pyplot (it comes automatically through pandas).
The problem may then be that the legend is hidden by the bars. The reason for that is that the legend resides in the first (lower) axes. There are two options.
We could move it to the secondary axes and then also change its location.
leg = ax.get_legend() leg.remove() # remove it from ax ax2.add_artist(leg) # add it to ax2 leg._set_loc(4)
Where the the loc
4
means "lower left" and is one of the codes to place the legend.We can move it out of the plot, (as in How to put the legend out of the plot)
leg._set_loc(2) leg.set_bbox_to_anchor((1.1,1)) ax.figure.subplots_adjust(right=0.6) # make space for the legend outside
Post a Comment for "Pandas Plot Multiple Series But Only Showing Legend For One Series"