简体   繁体   中英

Plot histogram with index values on x axis and frequencies of each column value on y axis

Based on the dataframe

import pandas as pd
df = pd.DataFrame({'cat1':[100,0,0,5],'cat2':[5,20,50,0]})
df 
    cat1    cat2
0   100 5
1   0   20
2   0   50
3   5   0

I want to plot a histogram such that the x axis represent the index values 0 to 3 and the bars for each index value show the distribution of the column values cat1 and cat2.

df.plot.hist(alpha=0.5)

plots the index values on the y and the category values on the x axis:

在此处输入图片说明

And

df.transpose().plot.hist(alpha=0.5)

results in something I don't even fully understand:

在此处输入图片说明

What I actually want is a bar for each index value, that illustrates the values in the columns - eg for index 0, there should be a bar in cat1 color stretching to 100 on the y axis, containing another bar in cat2 color stretching to 5.

How can I achieve that?

you can use the pandas viz functions :

df.plot.bar(stacked=True)

Try this, it's close that what you want:

import matplotlib.pyplot as plt

df.plot.barh()
plt.show()

Update thanks to SpghttCd:

import matplotlib.pyplot as plt

df.plot.bar()
plt.show(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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