Create a legend with Pandas and Matplotlib.pyplot

To create a legend with Pandas and matplotlib.pyplot, we can plot DataFrame data and enable the legend parameter. The legend helps identify different data series in the plot.

Steps to Create a Legend

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a DataFrame with multiple columns for plotting.
  • Plot the DataFrame using plot() method with legend=True.
  • Display the figure using show() method.

Example

Let's create a bar chart with a legend showing two data series ?

import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()

df = pd.DataFrame({'Numbers': [3, 4, 1, 7, 8, 5], 'Frequency': [2, 4, 1, 4, 3, 2]})
df.plot(ax=ax, kind='bar', legend=True)

plt.show()

Customizing the Legend

You can customize the legend position and appearance ?

import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [8.00, 4.00]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame({
    'Sales': [100, 150, 120, 180, 200],
    'Profit': [20, 30, 25, 40, 50]
})

ax = df.plot(kind='line', marker='o', legend=True)
ax.legend(loc='upper left', title='Metrics')
ax.set_title('Sales and Profit Trends')
ax.set_xlabel('Period')
ax.set_ylabel('Amount')

plt.show()

Legend Parameters

Parameter Description Example Values
legend Enable/disable legend True, False
loc Legend position 'upper left', 'center', 'best'
title Legend title String value

Conclusion

Use legend=True in DataFrame plot methods to automatically create legends. Customize legend appearance using ax.legend() with parameters like loc and title for better visualization.

Updated on: 2026-03-25T22:43:22+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements