Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas plotting dataframe specific column count as bar

If I have a data frame as below

column1                column2
key1Str         valueAsString1
key2Str         valueasString2
key2Str         valueasString1
key1Str         valueasString2
key3Str         valueasString1
key1Str         valueasString2

I wanted to plot this as bar graph where x-axis is each key and each value and y should be count of each value in data frame. I'm fairly new to python and tried to do as follows.

plot summary as (key1 - value1Count, value2Count, key2- value1Count, value2Count....)

fig, ax = plt.subplots()
for key in df['column1'].unique():
    data_=df[df['column1']==key]
    data_['column2'].values_count().plot(kind='bar', ax=ax)
plt.show()

it just shows one graph at the end, what's the better way to do this?

like image 865
SKR Avatar asked Dec 02 '25 14:12

SKR


1 Answers

IIUC:

import seaborn as sns

sns.barplot(x='column1', y='cnt', hue='column2',
            data=df.groupby(df.columns.tolist()).size().to_frame('cnt').reset_index())

enter image description here

like image 164
MaxU - stop WAR against UA Avatar answered Dec 04 '25 07:12

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!