【问题标题】:Pandas and combine stacked bar and line graphPandas 和组合堆积条形图和折线图
【发布时间】:2020-12-01 10:23:45
【问题描述】:

我已经对 pandas 数据框进行了分组:

        DailyTests  pos_DailyTests  percentOfPositive
Week                                               
44          1079              45               4.00
45         14593             706               4.64
46         18290            1003               5.14
47         19271            1237               6.07
48         12258             938               7.04

我想根据这些数据绘制图表。 “周”是 x 轴,前两列是堆积条形图,第三列应该是折线图。但该行不显示

我的代码:

fig , ax1 = plt.subplots()
ax2 = ax1.twinx()
data_con2.plot(kind='bar', stacked = True, ax=ax1, y = ['DailyTests','pos_DailyTests'])
data_con2.plot(kind='line', ax=ax2, y = 'percentOfPositive', color="red")
ax1.set_ylabel('Tests in day')
ax2.set_ylabel('percent of positives')

示例图如下:

Example graph - stacked bars but not the line graph

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您的代码无法正常工作的原因是 kind = 'bar' 和 'line' 都以不同的方式绘制 x 轴。解决这个问题的简单方法是将 week 转换为字符串类型。线图的另一件事很难看到,因为与其他两列相比,“percentOfPositive”的值较低,但确实存在。

    df['Week'] = df['Week'].astype("string") 
    ax = df[['Week', 'DailyTests', 'pos_DailyTests']].plot(x='Week', kind='bar',  stacked=True )
    df[['Week', 'percentOfPositive']].plot(x='Week', color ='black' ,marker='o',ax=ax)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      相关资源
      最近更新 更多