Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put legend outside the plot with pandas

How is it possible to put legend outside the plot?

import pandas as pd import matplotlib.pyplot as plt a = {'Test1': {1: 21867186, 4: 20145576, 10: 18018537},     'Test2': {1: 23256313, 4: 21668216, 10: 19795367}}  d = pd.DataFrame(a).T #print d  f = plt.figure()  plt.title('Title here!', color='black') plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) d.plot(kind='bar', ax=f.gca()) plt.show() 
like image 346
user977828 Avatar asked May 09 '14 03:05

user977828


People also ask

How do you make a legend outside the plot in Python?

In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.

How do you add a legend to the outside of a chart?

To place the legend outside of the axes bounding box, one may specify a tuple (x0, y0) of axes coordinates of the lower left corner of the legend. places the legend outside the axes, such that the upper left corner of the legend is at position (1.04, 1) in axes coordinates.

How do I change the location of my legend in Python?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.


1 Answers

I think you need to call plot before you add the calling legend.

import pandas as pd import matplotlib.pyplot as plt a = {'Test1': {1: 21867186, 4: 20145576, 10: 18018537},     'Test2': {1: 23256313, 4: 21668216, 10: 19795367}}  d = pd.DataFrame(a).T #print d  f = plt.figure()  plt.title('Title here!', color='black') d.plot(kind='bar', ax=f.gca()) plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) plt.show() 

----- Panda solution If you are using pandas Dataframe.plot

dataframe_var.plot.bar().legend(loc='center left',bbox_to_anchor=(1.0, 0.5)); 
like image 59
Phil Avatar answered Oct 06 '22 04:10

Phil