MBasith
MBasith

Reputation: 1499

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. 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:

               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: plot chart output

Upvotes: 0

Views: 957

Answers (1)

Gerges
Gerges

Reputation: 6519

Things I think you can do, but I think you want # 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).
  3. Change ylim range: 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'})

Upvotes: 1

Related Questions