简体   繁体   中英

Seaborn histogram/displot subplots

I have a dataframe, df, which has different rates for multiple 'N' currencies over a time period.

date         pair       rate
2019-05-01   AUD/USD   -0.004
2019-05-01   GBP/USD    0.05
2019-05-01   USD/NOK    0.0002      
...
2020-01-01   AUD/USD   -0.025
2020-01-01   GBP/USD    0.021315
2020-01-01   USD/NOK    0.0045

I would like to do a loop to plot N histograms (one per pair) using Seaborn sns; adding a title name that states the pair name on each plot.

I 'can achieve the plots using a simple groupby:

df.groupby('pair').hist(bins=20, normed=True)
plt.show()

However, this doesn't give me the individual titles and I would like to add more features to the plot.

You can use seaborn.FaceGrid for these types of plots.

g = sns.FacetGrid(data=df, row='pair')
g.map(sns.distplot, 'rate')

在此处输入图像描述

Iterate on your df selecting the slices for each unique value, make a distplot for each slice.

for pair in df.pair.unique():
    sns.distplot(df.loc[df.pair == pair,'rate'])
    plt.title(pair)

import pandas as pd
import seaborn as sns

# sample data
data = {'date': ['2019-05-01', '2019-05-01', '2019-05-01', '2020-01-01', '2020-01-01', '2020-01-01'],
        'pair': ['AUD/USD', 'GBP/USD', 'USD/NOK', 'AUD/USD', 'GBP/USD', 'USD/NOK'],
        'rate': [-0.004, 0.05, 0.0002, -0.025, 0.021315, 0.0045]}
df = pd.DataFrame(data)

# plot
g = sns.displot(data=df, x='rate', col='pair', common_bins=True)

在此处输入图像描述

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