python - Creating legend in matplotlib after plotting two Pandas Series -


i plotted 2 pandas series same dataframe same x axis , worked out fine. however, when tried manually create legend, appears title , not content. i've tried other solutions without luck. here's code:

    fig = plt.figure()     ax1 = fig.add_subplot(111)     ax2 = ax1.twinx()      width = .3      df.tally.plot(kind='bar', color='red', ax=ax1, width=width, position=1, grid=false)     df.costs.plot(kind='bar', color='blue', ax=ax2, width=width, position=0, grid=true)      ax1.set_ylabel('tally')     ax2.set_ylabel('total cost')      handles1, labels1 = ax1.get_legend_handles_labels()     handles2, labels2 = ax2.get_legend_handles_labels()      plt.legend([handles1, handles2], [labels1, labels2], loc='upper left', title='legend')     plt.show()     plt.clf() 

maybe have reason way, if not, easier:

in [1]: import pandas pd import numpy np import matplotlib.pyplot plt # optional, better looking import seaborn sns  # generate random data df = pd.dataframe(np.random.randn(10,3), columns=['tally', 'costs', 'other']) df[['tally', 'costs']].plot(kind='bar', width=.3) plt.show();  out[1]: 

plot


edit

after learning because have different scale other one, here's pandas approach:

# generate same data jianxun li np.random.seed(0) df = pd.dataframe(np.random.randint(50,100,(20,3)), columns=['tally', 'costs', 'other']) df.costs = df.costs * 5  width = .3  df.tally.plot(kind='bar', color='#55a868', position=1, width=width, legend=true, figsize=(12,6)) df.costs.plot(kind='bar', color='#4c72b0', position=0, width=width, legend=true, secondary_y=true)  plt.show(); 

enter image description here


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -