Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 display the legend, it only shows a legend for the second series.

Below is my code:

ax=nps_funding_month[35:][nps_funding_month['count_ratings']>=100].set_index('funding_month')['nps_percentage'].\
plot(kind='line',color='green',label='NPS')

plt.ylabel('Net Promoter Score')

ax=nps_funding_month[35:][nps_funding_month['count_ratings']>=100].set_index('funding_month')['count_ratings'].\
plot(kind='bar',secondary_y=True,label='Count of Ratings')

plt.ylabel('Count Ratings')

plt.legend()

plt.title('Net Promoter Score by Funding Month\n(Only Funding Months with at Least 100 Reviews)')

Picture of Output

like image 432
Pcarlitz Avatar asked Oct 20 '25 06:10

Pcarlitz


1 Answers

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

enter image description here

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.

  1. 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.

  2. 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
    
like image 164
ImportanceOfBeingErnest Avatar answered Oct 21 '25 21:10

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!