简体   繁体   中英

Ploting Lineplot for Each Category using Groupby and For Loop

I want to make a subplot of lineplot for each product using groupby for the following dateset:

#Create DataFrame
df = pd.DataFrame({'day': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
                   'product': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
                   'sales': [4, 7, 8, 12, 15, 8, 11, 14, 19, 20]})

# Glimpse of DataFrame
df

    day product sales
0   1    A     4
1   2    A     7
2   3    A     8
3   4    A     12
4   5    A     15
5   1    B     8
6   2    B     11
7   3    B     14
8   4    B     19
9   5    B     20

I'm trying the following code with for loop because I'd like to add axvline for each product later:

fig, ax = plt.subplots()
for k, v in df.groupby('product'):
    v.plot(x='day', y='sales', label=k, ax=ax)

However, I'm getting the following plot, and I want separate lineplot for each product. 在此处输入图像描述

What would be the smartest way of doing it? Any suggestions would be appreciated. Thanks!

You can try this:

import matplotlib.pyplot as plt

colors = ['b', 'r']
fig, ax = plt.subplots(1, 2) # 1 row, 2 columns

for i, (k, v) in enumerate(df.groupby('product')):
    v.plot(x='day', y='sales', c=colors[i], label=k, ax=ax[i])
    ax[i].axvline(i+3) # add a vertical line

It gives:

地块

Alternatively, with seaborn:

import seaborn as sns

g = sns.relplot(data=df,
                x="day",
                y="sales",
                hue='product',
                col='product',
                kind='line')

# add a vertical line
for i, ax in enumerate(g.axes[0]):
    ax.axvline(i+3)

which gives:

seaborn_plots

Based on what I understood, to generate multiple lineplots for each product:

First one is using seaborn.FacetGrid, which will provide you with multiple line plots for each product category.

import seaborn as sns
graph = sns.FacetGrid(df, col ="product")
graph.map(plt.plot, "day", "sales")
plt.show()

This will give you an output like this: 在此处输入图像描述

Or else, you can also use plt.plot to give you multiple lineplots.

lst = df['product'].unique()
for ls in lst:
    df1 = df[df['product'] == ls]
    plt.plot('day','sales',data=df1)
    plt.title(f'Product {ls}')
    plt.show()

在此处输入图像描述 This will create a new df and then plot it seperately.

Personally, I prefer the first option more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM