Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

python - 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: countplot 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.

question from:https://stackoverflow.com/questions/65598557/plotting-categorial-data-as-a-lineplot-in-seaborn

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...