简体   繁体   中英

How to plot multiple histograms for unique values from a column using Seaborn?

I am experiencing certain difficiulties plotting multiple histograms for unique values from a column and I couldn't find any topic on this so I appreciate your help in advance.

I have a table from which I need to take 2 columns: one with unique names of sports (Soccer, Volleyball, Hockey etc.) and another one with number of visits that represents number of people visited each type of sports in certain months. Apart from it there are much more columns in this table however the idea is to take only 2 of it and to plot multiple histograms using Seaborn.

Let's say it looks like this:

Sports - Visits

Soccer - 12300
Hockey - 7500
Volleyball - 3600
Hockey - 6800
Volleyball - 5300
Soccer - 9100
Hockey - 4800
etc.

The solution I found was not the best and considers converting my current table to pivot where names of sports are represented as features (columns) and visits are represented as values.

Then you can run something like this:

for i in enumerate(df.columns):
    plt.subplot(3, 7, i[0]+1)
    sns.histplot(task321[i[1]], bins=20)

and get this: 在此处输入图像描述

Is there an easier way of doing this without making extra pivot tables with names as features?

I think what you want here is FacetGrid.map()

Documentation here

import pandas as pd
import seaborn as sns

cols = ['Sports','Visits']


data = [['Soccer',12300],
        ['Hockey',7500],
        ['Volleyball',3600],
        ['Hockey',6800],
        ['Volleyball',5300],
        ['Soccer',9100],
        ['Hockey',4800]]

df = pd.DataFrame(data, columns=cols)
  
g = sns.FacetGrid(df, col="Sports")
g.map(sns.histplot, "Visits")
#g.map(sns.histplot, "Visits", bins=20) #<-- or to set bins

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM