messy748
messy748

Reputation: 327

How to split a line graph into subplots in Python?

Currently I have a line plot that graphs everything together:

import seasborn as sns
sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType')

Which creates this graph fine

enter image description here

However, I am looking to split each category into its own subplot. I've tried this by

f, axes =  plt.subplots(3, 2, figsize=(12, 6), sharex=True, sharey=True)

sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType' == 'Tornado', ax=axes[0,0], legend=False)
sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType' == 'Flood', ax=axes[0,1], legend=False)
sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType' == 'Fire', ax=axes[1,0], legend=False)
sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType' == 'Hurricane', ax=axes[1,1], legend=False)
sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType' == 'Severe Storm(s)', ax=axes[2,0], legend=False)
sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType' == 'Snow', ax=axes[2,1], legend=False)

But it doesn't work as I intend. It seems to be repeating the same graph over each time

enter image description here

I am simply looking to split each of the line graphs in the original plot to its own subplot, but I'm not quite sure what I'm doing wrong.

Also as a side note, is there a better, more intricate way to plot each sub plot without literally copy and pasting for each different category?

Upvotes: 1

Views: 3620

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40707

What you are trying to do is syntactically incorrect, You should write:

f, axes =  plt.subplots(3, 2, figsize=(12, 6), sharex=True, sharey=True)

sns.lineplot(data=years_total[years_total.incidentType=='Tornado'], x='fyDeclared', y='count', ax=axes[0,0], legend=False)
sns.lineplot(data=years_total[years_total.incidentType=='Flood'], x='fyDeclared', y='count', ax=axes[0,1], legend=False)
(...)

However, to avoid the tedious repetitions, you could take advantage of seaborn's FacetGrid, which is exactly made for this purpose. FacetGrid creates a figure where each row/column correspond to a particular value of a categorical variable. Therefore:

idx = pd.date_range(start='1950-01-01', end='2019-12-31', periods=100)
df = pd.DataFrame()
for type in ['Flood','Fire','Tornado']:
    temp = pd.DataFrame({'fyDeclared':idx, 'count':np.random.random(100), 'incidentType':type})
    df = pd.concat([df,temp])

g = sns.FacetGrid(data=df, col='incidentType', col_wrap=2)
g.map(sns.lineplot, 'fyDeclared', 'count')

enter image description here

Upvotes: 2

Related Questions