简体   繁体   中英

Plotting categorial data as a lineplot in seaborn

I am trying to duplicate what a Seaborn countplot is able to do, but with a lineplot. Below is a code sample showing what countplot is doing:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df=pd.DataFrame({
    'date' : ['2020-01-01', '2020-01-01', '2020-01-01', '2020-01-02', '2020-01-02', '2020-01-02', '2020-01-03'],
    'type' : ['A', 'B', 'B', 'B', 'A', 'A', 'C']
    })

sns.countplot(
    data=df, x=df['date'], hue=df['type'])
plt.show()

which produces this graph: 计数图

I want to do the same thing, but with a line graph, so that x= date, y= amount of type for that date, and hue= type.

So my question is... Is this possible? I have tried with multiple different Seaborn graphs (relplot, lineplot, etc) and have not got this to work.

IIUC, you can do it by first get the size of each date and type with groupby.size and use lineplot with the transformed dataframe.

sns.lineplot(
    data=df.groupby(['date','type']).size().reset_index(name='count'), 
    x='date', y='count', hue='type')

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