【问题标题】:Python Matplotlib Plotting Stacked Bar ChartPython Matplotlib 绘制堆积条形图
【发布时间】:2018-03-10 19:18:41
【问题描述】:

我正在尝试从具有两个系列的数据框中绘制堆积条形图。第二个系列的数据量非常少,但我希望它在图表中仍能以栗色小线的形式出现。当我将图表保存为 png 文件时,前两个条不显示第二个“驱动程序”数据集。然而,随后的条形图都显示了它们。下面是我使用的代码以及图表的快照。您可以看到前两个栏中没有显示“驱动程序”系列?我该如何解决这个问题?

代码:

df_trend = pd.read_csv('test_log.csv', index_col=0, skiprows=0)
df_trend.index = (pd.to_datetime(df_trend.index)).strftime("%m/%d %H:00")

fig = plt.figure()
rcParams['figure.figsize'] = df_trend.shape[0], 4
ax = fig.add_subplot(111)
y = df_trend.tail(24).plot.bar(stacked=True, color=['skyblue', 'maroon'], edgecolor="none", width=0.2)
y.legend(loc="lower left", fontsize=9)
plt.tick_params(axis='both', which='both', labelsize=9)
fig.autofmt_xdate()

plt.title('Cars vs Drivers', fontsize=10, y=1.05)
plt.savefig('cars_drivers.png', bbox_inches='tight')
plt.close()

使用的数据帧:

               Cars  Drivers
09/27 09:00  243000      300
09/28 09:00  243970      190
09/28 13:00  267900      290
09/28 17:00  254770      180
09/28 18:00  250860      290

图表:

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    我认为你可以做的事情,但我认为你想要#2:

    1. 不要使用堆积条形图(这是我的首选)。
    2. 增加图形的DPI:plt.savefig('cars_drivers.png', bbox_inches='tight',dpi=1000)
    3. 更改ylim 范围:plt.ylim([200e3, 300e3])
    4. 更改驱动程序的比例并重命名列以显示在图例中:

      df_trend['Drivers'] = 10*df_trend['Drivers']

      df_trend = df_trend.rename(columns={'Drivers': 'Drivers x 10'})

    【讨论】:

    • 首先感谢您提供多种解决方案。我也同意解决方案 1 是最好的,但收件人需要一个堆叠的条形图。我尝试了所有选项,但选项 3 是唯一对我有用的选项。谢谢 Gerges。
    猜你喜欢
    • 2018-11-26
    • 2019-09-27
    • 2012-09-17
    • 2021-12-27
    • 2018-01-17
    • 2019-11-28
    • 2023-03-11
    • 2016-05-24
    相关资源
    最近更新 更多