Home > Software design >  Use pandas df column as legend label?
Use pandas df column as legend label?

Time:11-18

When plotting a pandas Datafarme column is it possible to use the Dataframe column name as the legend label instead of explicitly specifying the label?

Example:

import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame(data={'col1': [0, 2, 1, 3], 
                        'col2': [9,7,8,9]}, 
                        index=[0, 1, 2, 3])

f = plt.figure()
ax = f.subplots()
ax.plot(df['col1'], label='col1') # How to not explicitly specify label?
# ax.plot(df['col1']) # This does not produce a legend label
ax.legend()

CodePudding user response:

Use the pandas plotting API:

fig, ax = plt.subplots()
df['col1'].plot(ax=ax)
ax.legend()
  • Related