[英]Plotting two different kind of plots next to each other (Seaborn, FacetGrid)
[英]Plotting seaborn histogram from each column in different subplots (facetgrid)
我的結構遵循熊貓數據幀:
n X Y Z
0 1.000000 1.000000 1.014925
1 1.000000 1.000000 1.000000
我想從每列創建 M 個單獨的子圖(直方圖)。 一張直方圖來自 X,一張來自 Y,最后一張來自 Z。
我希望它有不同的情節。 我正在查看https://seaborn.pydata.org/generated/seaborn.FacetGrid.html ,但我不明白如何從我的數據中繪制它的語法/邏輯。
您可以使用 Pandas 數據框的內置plot
方法和選項subplots=True
按列繪圖
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
需要很多其他參數來讓你輕松地改變你的情節,例如
df.plot.hist(subplots=True, legend=True, layout=(1, 3))
使用seaborn.FacetGrid
可能需要您重構數據。
讓我們看一個例子:
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')
[出去]
sns.pairplot(your_df)
將執行此操作,但是它還會向您顯示每列的成對散點圖,所以是的,它會做得比您需要的多一點? 在進行探索性數據分析時很好。 您還可以通過在調用中添加corner=True
使其更簡潔。
或類似的東西:
# 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.