Put legend outside the Matplotlib plot with Pandas in Python

In this tutorial, you will learn how to put Legend outside the plot using Python with Pandas.

A legend is an area of a chart describing all parts of a graph. It is used to help readers understand the data represented in the graph.

Libraries Used:

We will be using 2 libraries present in Python.

  • Pandas
    This is a popular library for data analysis.
  • Matplotlib
    Matplotlib is a multiplatform data visualization library that is used to produce 2D plots of arrays, such as a line, scatter, bar etc.

Syntax:

pd.DataFrame().T
This function is used to perform a transpose of the rows and columns by writing the rows as columns and columns as rows. T is used to access the transpose() function.
plt.figure()
This function of the matplotlib library is used to create a figure.
plt.title(' ', color=' ')

This function is used to give the title for the plotted figure, and the argument color specifies the font color of the text.

d.plot(kind=' ',ax=f.gca())

This is used to specify the kind of chart we need such as line, bar.
‘line’ – line plot
‘bar’ – vertical bar plot
‘hist’ – histogram
‘pie’ – pie plot
‘scatter’ – scatter plot
ax is a matplotlib axes object and .gca() is used to get the current axes instance for the figure.

plt.legend(loc=' ',bbox_to_anchor=())

This function is used to specify the location and the exact coordinates to display the legend in the figure.
loc – specifies the location of the legend
bbox_to_anchor – states the exact coordinates of the legend.

plt.show()

This function is used to display the plotted figure.

Python program: Put legend outside the Matplotlib plot with Pandas

import pandas as pd
import matplotlib.pyplot as plt
data = {'1': {1: 20, 2: 21, 3: 22},
    '2': {1: 23, 2: 24, 3: 25}}

d = pd.DataFrame(data).T
f = plt.figure()
plt.title('Legend Outside', color='black')
d.plot(kind='bar', ax=f.gca())
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()

The output of the above program is given in the figure below:

legend outsid output in Python matplotlib

Leave a Reply

Your email address will not be published. Required fields are marked *