【问题标题】:Plot columns of data-frame based on conditions of other columns in Python根据 Python 中其他列的条件绘制数据框的列
【发布时间】:2020-04-13 11:54:10
【问题描述】:

下面是我的数据集:

    City    Product Spend_Year  Total_Spend
0   BANGALORE   Gold    2004    248006886
1   BANGALORE   Gold    2005    357076946
2   BANGALORE   Gold    2006    329375735
3   BANGALORE   Platimum    2004    138238363
4   BANGALORE   Platimum    2005    167115119
... ... ... ... ...
67  TRIVANDRUM  Platimum    2005    222789632
68  TRIVANDRUM  Platimum    2006    129408676
69  TRIVANDRUM  Silver  2004    14957733
70  TRIVANDRUM  Silver  2005    27465271
71  TRIVANDRUM  Silver  2006    31632500

我需要绘制 CityTotal_Spend,同时为所有可能的组合选择一个 productSpend_Year

示例:2004 年黄金产品的 CityTotal_Spend 的关系图。

P.S.:在数据集中,我有 3 个产品类别,数据可用 3 年。

任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x pandas matplotlib seaborn


    【解决方案1】:

    你可以使用seaborn.FaceGrid:

    g = sns.FacetGrid(data=df, row='Spend_Year', col='Product')
    g = g.map(sns.lineplot, 'City', 'Total_Spend')
    

    或者你可以使用groupby():

    fig, axes = plt.subplots(3,3)
    
    for (k,d), ax in zip(df.groupby(['City','Spend_Year']), axes.ravel()):
        city, year = k
        d.plot(x='City', y='Total_Spend', ax=ax)
    
        # extra format with ax if needed
        ax.set_title(f'{city} - {year}')
    

    【讨论】:

      【解决方案2】:

      下面的代码将为每个组合绘制一个图。使用 matplotlib 子图将它们全部移动到一个图中应该很容易。

      import matplotlib.pyplot as plt
      for product in df['Product'].unique():
          for syear in df['Spend_Year'].unique():
              plt.figure()
              ax = df.query('Product==@product and Spend_year==@syear').set_index('City')['Total Spend'].plot()
              ax.set_title(f'Product {product} year {syear}')
      

      【讨论】:

        猜你喜欢
        • 2017-12-26
        • 1970-01-01
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多