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()
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With