简体   繁体   中英

Plotting seaborn histogram from each column in different subplots (facetgrid)

My structure is following pandas DataFrame:

n    X              Y          Z
0   1.000000    1.000000    1.014925    
1   1.000000    1.000000    1.000000    

I want to create M separate subplots (histogram) from each column. One histogram would be from X, one from Y and the last one from Z.

I would like it to have on separate plots. I was looking into https://seaborn.pydata.org/generated/seaborn.FacetGrid.html , but I don't understand the syntax/logic how to plot it from my data.

You can use the inbuilt plot method of your pandas dataframe and the option subplots=True to plot by column

from io import StringIO
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn')

# Here I read your example data in
df = pd.read_fwf(StringIO("""
    X              Y          Z
0   1.000000    1.000000    1.014925    
1   1.000000    1.000000    1.000000
"""), header=1, index_col=0)

# Plotting as desired
df.plot.hist(subplots=True, legend=False)

在此处输入图片说明

df.plot takes lots of other arguments to allow you to easily alter your plot, eg

df.plot.hist(subplots=True, legend=True, layout=(1, 3))

在此处输入图片说明

Using seaborn.FacetGrid may require you to restructure your data.

Lets look at an example:

np.random.seed(0)
df = pd.DataFrame(np.random.randn(1000, 3), columns=['X', 'Y', 'Z'])
print(df.head(10))

          X         Y         Z
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
2  0.950088 -0.151357 -0.103219
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863
5  0.333674  1.494079 -0.205158
6  0.313068 -0.854096 -2.552990
7  0.653619  0.864436 -0.742165
8  2.269755 -1.454366  0.045759
9 -0.187184  1.532779  1.469359

df_melted = df.melt(var_name='column')

print(df_melted.head(10))

  column     value
0      X  1.764052
1      X  2.240893
2      X  0.950088
3      X  0.410599
4      X  0.761038
5      X  0.333674
6      X  0.313068
7      X  0.653619
8      X  2.269755
9      X -0.187184


g = sns.FacetGrid(df_melted, row='column')
g.map(plt.hist, 'value')

[out]

在此处输入图片说明

sns.pairplot(your_df) will do this, however it'll also show you pairwise scatterplots for each column, so yes and it'll do a bit more then you need? Good when doing exploratory data analysis. You can also make it a bit cleaner by adding corner=True to the call.

Or something like:

# Update as needed
n_rows=1
n_cols=3

# Create the subplots
fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols, figsize=(10, 10))
for i, column in enumerate(df):
    sns.histplot(df, ax=axes[i // n_cols, i % n_cols]).set_title(column)

https://seaborn.pydata.org/generated/seaborn.pairplot.htma

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