Home > Enterprise >  Pandas plot stacked and unstacked bar
Pandas plot stacked and unstacked bar

Time:04-11

I am new to pandas. I am trying to visualize the time my program takes for different tasks. I read my logs and calculated the average time, and it now looks like this: enter image description here

As I have only one row, I need to draw these tree time values in a bar plot. Time1 should be a single bar and Time2 and Time3 being combined. Time3 is supposed to be on top of Time2 with a different color. What i did so far is:

axis = time_pd.plot(kind='bar', ylabel="Time [sek]", xlabel="Phase", figsize=(11,11), rot=0)
legend = axis.legend(["time1", "time2", "time3"], fontsize=26, loc='center left', bbox_to_anchor=(1.0, 0.93))

The result is 3 bars on only one label on the x-axis: enter image description here

Can someone give me any advice how to set up 2 Bars with Time1 and Time2 with Time3 being on top of Time2?

CodePudding user response:

The solution is to plot to figures and merge the result.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'time1':[3], 'time2':[2], 'time3':[1]})

ax = df['time1'].plot.bar(ylabel="Time [sek]", xlabel="Phase", figsize=(8,8), color='green', position=1)
df[['time2', 'time3']].plot.bar(stacked=True, sharex=True, ax=ax, position=0)
legend = ax.legend(["time1", "time2", "time3"], fontsize=12, loc='center left', bbox_to_anchor=(1.0, 0.93))
plt.xlim([-1, 1])
plt.show()

Output

bar plot with stacked part

Comment

I use pandas.plot twice, the first time "plain" and the second time "stacked". This normally produces two figures. To have only one, I re-use the axis by ax=ax in the second call.

To avoid that both plots are on each other and the first can not be seen, I use the position keyword. The limits for the x-axis have to be set, too, or some parts of the plot are outside of the visual area.

  • Related