简体   繁体   English

Python Matplotlib绘制堆积条形图

[英]Python Matplotlib Plotting Stacked Bar Chart

I'm attempting to plot a stacked bar chart from a data frame with two series. 我正在尝试从具有两个系列的数据框中绘制堆积的条形图。 The second series has a very small amount of data but I expect it to still be visible in the chart as a small maroon line. 第二个系列的数据非常少,但我希望它在图表中仍显示为一条栗色的细线。 When I save the chart as a png file the first two bars do not show the second "Drivers" dataset. 当我将图表另存为png文件时,前两个条形图不显示第二个“驱动程序”数据集。 However subsequent bars all show them. 但是,随后的所有条都将其显示。 Below is the code I am using along with the snapshot of the chart. 以下是我正在使用的代码以及图表的快照。 You can see that the "Drivers" series is not showing in the first two bars? 您可以看到“驱动程序”系列未在前两个栏中显示吗? How can I remedy this? 我该如何补救?

Code: 码:

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

DataFrame Used: 使用的DataFrame:

               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

Chart: 图表: 绘图图输出

Things I think you can do, but I think you want # 2: 我认为您可以做的事情,但是我想做的#2:

  1. Don't use a stacked bar plot (this is my first choice). 不要使用堆积的条形图(这是我的首选)。
  2. Increase DPI of figure: plt.savefig('cars_drivers.png', bbox_inches='tight',dpi=1000) . 增加数字的DPI: plt.savefig('cars_drivers.png', bbox_inches='tight',dpi=1000)
  3. Change ylim range: plt.ylim([200e3, 300e3]) . 更改ylim范围: plt.ylim([200e3, 300e3])
  4. Change scale of drivers and rename column to show in legend: 更改驱动程序的比例并重命名以在图例中显示的列:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM