Plotting series using seaborn
Asked Answered
G

2

10
category = df.category_name_column.value_counts()  

I have the above series which returns the values:

CategoryA,100
CategoryB,200

I am trying to plot the top 5 category names in X - axis and values in y-axis

head = (category.head(5)) 
sns.barplot(x = head ,y=df.category_name_column.value_counts(), data=df)

It does not print the "names" of the categories in the X-axis, but the count. How to print the top 5 names in X and Values in Y?

Gem answered 17/10, 2017 at 15:9 Comment(0)
W
33

You can pass in the series' index & values to x & y respectively in sns.barplot. With that the plotting code becomes:

sns.barplot(head.index, head.values)

I am trying to plot the top 5 category names in X

calling category.head(5) will return the first five values from the series category, which may be different than the top 5 based on the number of times each category appears. If you want the 5 most frequent categories, it is necessary to sort the series first & then call head(5). Like this:

category = df.category_name_column.value_counts()
head = category.sort_values(ascending=False).head(5)
Winkle answered 17/10, 2017 at 15:28 Comment(0)
C
3

Since the previous accepted solution is deprecated in seaborn. Another workaround could be as follows:

  1. Convert series to dataframe
category = df.category_name_column.value_counts()  
category_df = category.reset_index()
category_df.columns = ['categories', 'frequency']
  1. Use barplot
ax = sns.barplot(x = 'categories', y = 'frequency', data = category_df)

Although this is not exactly plot of series, this is a workaround that's officially supported by seaborn.

For more barplot examples please refer here:

  1. https://seaborn.pydata.org/generated/seaborn.barplot.html
  2. https://stackabuse.com/seaborn-bar-plot-tutorial-and-examples/
Cynosure answered 12/5, 2022 at 10:7 Comment(1)
Note that there's nothing deprecated about plotting a series in seaborn. The deprecation warning is only about whether x and y are implicit (deprecated) or explicit (supported), so the accepted answer is still fully supported as long as we specify x and y explicitly: sns.barplot(x=head.index, y=head.values)Helgoland

© 2022 - 2024 — McMap. All rights reserved.