目前,我有一个将所有内容都绘制在一起的折线图:
import seasborn as sns
sns.lineplot(data=years_total, x='fyDeclared', y='count', hue='incidentType')
哪个可以很好地创建此图
但是,我希望将每个类别分成自己的子图。我已经尝试过]
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)
但是它没有按我的预期工作。似乎每次都重复相同的图]
我只是想将原始图中的每个折线图拆分为自己的子图,但是我不确定自己在做什么错。
此外,还有一种更好,更复杂的方式来绘制每个子图,而不必为每个不同的类别进行字面复制和粘贴吗?
您试图做的在语法上是不正确的,您应该写:
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)
(...)
但是,为避免冗长的重复,您可以利用seaborn的FacetGrid
,它正是为此目的而制作的。 FacetGrid
创建一个图形,其中每个行/列对应于分类变量的特定值。因此:
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')