【问题标题】:How to split a line graph into subplots in Python?如何在 Python 中将折线图拆分为子图?
【发布时间】:2019-11-15 04:07:06
【问题描述】:

目前我有一个将所有内容绘制在一起的线图:

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)

但它并没有按我的意愿工作。它似乎每次都在重复相同的图表

我只是想将原始图中的每个折线图拆分为自己的子图,但我不太确定我做错了什么。

另外作为旁注,是否有更好、更复杂的方法来绘制每个子图,而无需为每个不同的类别逐字复制和粘贴?

【问题讨论】:

    标签: python matplotlib seaborn linegraph


    【解决方案1】:

    你试图做的在语法上不正确,你应该写:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 2015-10-24
      • 1970-01-01
      • 2015-07-15
      • 2022-11-30
      • 2011-08-22
      • 2022-06-21
      相关资源
      最近更新 更多