【问题标题】:Matplotlib plot bar chart with 2 columns relationship in dataframesMatplotlib 绘制条形图,在数据框中具有 2 列关系
【发布时间】:2021-01-22 13:31:39
【问题描述】:

我一直在绘制数据框。 这可能很简单,但我无法弄清楚!

我有这样的熊猫数据框记录:

    Year  occurrence   Count
0   2011           0     306
1   2011           1    1838
2   2012           0     422
3   2012           1    1816
4   2013           0     423
5   2013           1    3471
6   2014           0     537
7   2014           1    3239
8   2015           0     993
9   2015           1    7668
10  2016           0     415
11  2016           1    2052
12  2017           0     511
13  2017           1    4750
14  2018           0     705
15  2018           1    2125

我想将此数据框绘制为条形图,这样,x 轴包含年份,Y 轴包含计数。

  1. 现在我想根据出现值绘制此计数。表示在 2011 年,第一个柱的 count=306,第二个柱的 count=1838,其余年份相同。
  2. 另外,如果可能的话,我还必须显示基于同一事物的堆积条形图。
  3. 还有,如何绘制包含两条线的折线图?

    任何人都可以解决这个问题吗?

    我根据我的结果创建了示例 df:
df = spark.createDataFrame({
(2011,  0,   306),
(2011,  1,  1838),
(2012,  0,   422),
(2012,  1,  1816),
(2013,  0,   423),
(2013,  1,  3471),
(2014,  0,   537),
(2014,  1,  3239),
(2015,  0,   993),
(2015,  1,  7668),
(2016,  0,   415),
(2016,  1,  2052),
(2017,  0,   511),
(2017,  1,  4750),
(2018,  0,   705),
(2018,  1,  2125),
}, ['Year', 'occurrence', 'Count'])

pdf_1 = df.toPandas()

我试过这个:
pdf_1.plot(x='Year', y=['Count'], kind='bar')

但它并没有给我我想要的东西。

【问题讨论】:

    标签: pandas dataframe matplotlib pyspark


    【解决方案1】:

    你可以使用pivot来重塑:

    pdf_1.pivot('Year', 'occurrence', 'Count').plot.bar(stacked=True)
    

    输出:

    【讨论】:

    • 感谢@BigBen,快速解答!另外,您知道如何在相同条件下简单地绘制折线图和条形图(每年 2 个条形图)吗?
    【解决方案2】:

    根据@BigBen,

    三个答案我都想通了:

    # For Question 1
    pdf_1.pivot(index='Year', columns='above_threshold', values='Count').plot.bar()
    
    # For Question 2
    pdf_1.pivot('Year', 'above_threshold', 'Count').plot.bar(stacked=True)
    
    # For Question 3
    pdf_1.pivot(index='Year', columns='above_threshold', values='Count').plot.line()
    

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 2022-01-20
      • 2022-01-27
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多