Reputation: 117
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
Reputation: 62513
FacetGrid
is no longer recommended, and seaborn.distplot
is deprecated.sns.displot
, which is a figure-level plot.python 3.10
, pandas 1.4.2
, matplotlib 3.5.1
, seaborn 0.11.2
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)
Upvotes: 0
Reputation: 18647
You can use seaborn.FaceGrid
for these types of plots.
g = sns.FacetGrid(data=df, row='pair')
g.map(sns.distplot, 'rate')
Upvotes: 5
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