How to plot stacked time histogram starting from a Pandas DataFrame?

How to plot stacked time histogram starting from a Pandas DataFrame?



Consider the following DataFrame df:


df


Date Kind
2018-09-01 13:15:32 Red
2018-09-02 16:13:26 Blue
2018-09-04 22:10:09 Blue
2018-09-04 09:55:30 Red
... ...



In which you have a column with a datetime64[ns] dtype and another which contains a np.object which can assume only a finite number of values (in this case, 2).


datetime64[ns]


np.object



You have to plot a date histogram in which you have:



How is it possible to achieve this using Matplotlib?



I was thinking to do a set_index and resample as follows:


df.set_index('Date', inplace=True)
df.resample('1d').count()



But I'm losing the information on the number of items per Kind. I also want to keep any missing day as zero.



Any help very appreciated.




1 Answer
1



Use groupby, count and unstack to adjust the dataframe:


groupby


count


unstack


df2 = df.groupby(['Date', 'Kind'])['Kind'].count().unstack('Kind').fillna(0)



Next, re-sample the dataframe and sum the count for each day. This will also add any missing days that are not in the dataframe (as specified). Then adjust the index to only keep the date part.


df2 = df2.resample('D').sum()
df2.index = df2.index.date



Now plot the dataframe with stacked=True:


stacked=True


df2.plot(kind='bar', stacked=True)



enter image description here



Alternatively, the plt.bar() function can be used for the final plotting:


plt.bar()


cols = df['Kind'].unique() # Find all original values in the column
ind = range(len(df2))

p1 = plt.bar(ind, df2[cols[0]])
p2 = plt.bar(ind, df2[cols[1]], bottom=df2[cols[0]])



Here it is necessary to set the bottom argument of each part to be the sum of all the parts that came before.


bottom



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

How do I collapse sections of code in Visual Studio Code for Windows?