Bar plot type chart with unique values compounding the bars
Question:
I’m trying to create a graph using python that show each value that count, stacked, in a form of column.
df = pd.DataFrame()
df['hour']=['00:00', '00:00','01:00', '01:00','01:00','02:00','02:00','03:00','03:00','03:00','03:00','03:00','04:00','05:00','05:00','05:00']
df['event']=['abc','def','abc','def','ghj','def','klm','mno','klm','ghj','pqr','stu','def', 'abc','pqr','mno' ]
I’m expecting something like this:
A solution or any insight will be very welcome!
Answers:
Try to pivot your dataframe then draw your graph:
import matplotlib.pyplot as plt
# Pivot your dataframe and create a dummy column
df1 = df.assign(value=1).pivot_table(index='hour', columns='event',
values='value', fill_value=0)
# Use Pandas to draw your graph
ax = df1.plot.bar(stacked=True, rot=0, legend=False, width=1, color='blue')
# Fill each rectangle
labels = df1.mul(df1.columns).to_dict('list').values()
for c, l in zip(ax.containers, labels):
ax.bar_label(c, l, label_type='center', color='white')
# Customize your graph
ax.yaxis.set_major_locator(plt.NullLocator())
plt.show()
Output:
Details:
>>> df1
event abc def ghj klm mno pqr stu
hour
00:00 1 1 0 0 0 0 0
01:00 1 1 1 0 0 0 0
02:00 0 1 0 1 0 0 0
03:00 0 0 1 1 1 1 1
04:00 0 1 0 0 0 0 0
05:00 1 0 0 0 1 1 0
I’m trying to create a graph using python that show each value that count, stacked, in a form of column.
df = pd.DataFrame()
df['hour']=['00:00', '00:00','01:00', '01:00','01:00','02:00','02:00','03:00','03:00','03:00','03:00','03:00','04:00','05:00','05:00','05:00']
df['event']=['abc','def','abc','def','ghj','def','klm','mno','klm','ghj','pqr','stu','def', 'abc','pqr','mno' ]
I’m expecting something like this:
A solution or any insight will be very welcome!
Try to pivot your dataframe then draw your graph:
import matplotlib.pyplot as plt
# Pivot your dataframe and create a dummy column
df1 = df.assign(value=1).pivot_table(index='hour', columns='event',
values='value', fill_value=0)
# Use Pandas to draw your graph
ax = df1.plot.bar(stacked=True, rot=0, legend=False, width=1, color='blue')
# Fill each rectangle
labels = df1.mul(df1.columns).to_dict('list').values()
for c, l in zip(ax.containers, labels):
ax.bar_label(c, l, label_type='center', color='white')
# Customize your graph
ax.yaxis.set_major_locator(plt.NullLocator())
plt.show()
Output:
Details:
>>> df1
event abc def ghj klm mno pqr stu
hour
00:00 1 1 0 0 0 0 0
01:00 1 1 1 0 0 0 0
02:00 0 1 0 1 0 0 0
03:00 0 0 1 1 1 1 1
04:00 0 1 0 0 0 0 0
05:00 1 0 0 0 1 1 0