Home > OS >  How to create subplots with a title for each group of data in a dataframe
How to create subplots with a title for each group of data in a dataframe

Time:11-11

Let's say I have a data frame defined as below:

cat = ['games','games','home','home','home','food','food','food','food','food']
dates = ['2024-07-01','2021-31-1', '2021-04-1', '2021-05-1','2021-02-2', '2021-05-1','2021-01-2','2021-14-2','2021-03-3','2021-11-4']
nums = [137, 338, 52, 144, 100, 5, 72, 400, 100, 99]

df = pd.DataFrame({'cat':cat, 'dates':dates, 'nums':nums})

I want to plot each cat -- for example create a plot of the nums vs. dates for games, home, and food separately.

I get it by doing df.groupby('cat').plot(x = 'date'), which works, but I'm having trouble getting titles on each subplot. Or is there an easier way to achieve this and have each plot title be the name of the cat?

CodePudding user response:

You can iterate over the groups, and this gives you full control over the axes, titles, etc., of each plot

import matplotlib.pyplot as plt

for key, gp in df.groupby('cat'):
    gp.plot('dates')
    plt.title(key)

CodePudding user response:

  • The easiest way is the use seaborn, a high-level API for matplotlib, which works directly with long form data.
  • When using enter image description here

  • Related