pablo144
pablo144

Reputation: 117

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.

Upvotes: 2

Views: 943

Answers (3)

Trenton McKinney
Trenton McKinney

Reputation: 62513

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)

enter image description here

Upvotes: 0

Chris Adams
Chris Adams

Reputation: 18647

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

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

enter image description here

Upvotes: 5

Mattia Peracchi
Mattia Peracchi

Reputation: 58

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)

Upvotes: 1

Related Questions