Bra*_*ion 5 python matplotlib pandas seaborn
我的结构遵循熊猫数据帧:
n X Y Z
0 1.000000 1.000000 1.014925
1 1.000000 1.000000 1.000000
Run Code Online (Sandbox Code Playgroud)
我想从每列创建 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)
Run Code Online (Sandbox Code Playgroud)
df.plot
需要很多其他参数来让你轻松改变你的情节,例如
df.plot.hist(subplots=True, legend=True, layout=(1, 3))
Run Code Online (Sandbox Code Playgroud)
使用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')
Run Code Online (Sandbox Code Playgroud)
[出去]