SKR
SKR

Reputation: 127

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?

Upvotes: 3

Views: 853

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

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

Upvotes: 4

Related Questions