3

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thankx MaxU, this works per key count, I wanted to have separate bars per value as well, since the values are also shared across all keys and very limited
@SKR, do you mean something like: df.groupby(['column1','column2']).size().plot.bar()?
Thanks, yes group by both columns worked as expected, but through seaborn is much cleaner.
@SKR, glad I could help :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.