Oblomov
Oblomov

Reputation: 9665

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:

enter image description here

And

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

results in something I don't even fully understand:

enter image description here

What I actually want is a bar for each index value, that illustrates the values in the columns - e.g. 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?

Upvotes: 1

Views: 5157

Answers (2)

Amara BOUDIB
Amara BOUDIB

Reputation: 363

you can use the pandas viz functions :

df.plot.bar(stacked=True)

Upvotes: 1

Barthelemy Pavy
Barthelemy Pavy

Reputation: 570

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(

Upvotes: 0

Related Questions