简体   繁体   English

绘制多个子图,每个子图都使用 Seaborn 显示了 Pandas DataFrame 的两列之间的关系

[英]Plotting multiple subplots, each showing relation between two columns of a pandas DataFrame using Seaborn

I have a pandas DataFrame as follows:我有一个熊猫数据如下:

df=pd.DataFrame({'depth':[499,500,501,502,503],'parameter1':[25,29,24,23,25],'parameter2':[72,80,65,64,77]})

I wish to plot multiple (two in this case) seaborn lineplots under the same graph, as subplots.我希望在同一图下绘制多个(在这种情况下为两个)seaborn线图,作为子图。 I want to keep the depth parameter constant on the x-axis but vary the y-axis parameters as per the other column values.我想在x 轴上保持深度参数不变,但根据其他列值改变y 轴参数。

sns.relplot(x='depth',y="parameter1",kind='line',data=df)

parameter1 vs depth参数 1 与深度

sns.relplot(x='depth',y="parameter2",kind='line',data=df)

parameter2 vs depth参数 2 与深度

I have tried to use seaborn.FacetGrid() but I haven't obtained proper results with these.我曾尝试使用seaborn.FacetGrid()但我没有获得正确的结果。

Let me know how I can plot these graphs as subplots under a single graph without having to define them individually.让我知道如何将这些图形绘制为单个图形下的子图,而无需单独定义它们。

To use FacetGrid , you have to transform your dataframe in "long-form" using melt() .要使用FacetGrid ,您必须使用melt()以“长格式”转换数据FacetGrid

df=pd.DataFrame({'depth':[499,500,501,502,503],'parameter1':[25,29,24,23,25],'parameter2':[72,80,65,64,77]})
df2 = df.melt(id_vars=['depth'])

g = sns.FacetGrid(data=df2, col='variable')
g.map_dataframe(sns.lineplot, x='depth', y='value')

在此处输入图片说明

Note that the same output can be achieved more simply using relplot instead of creating the FacetGrid "by hand"请注意,使用relplot而不是“手动”创建FacetGrid可以更简单地实现相同的输出

sns.relplot(data=df2, x='depth', y='value', col='variable', kind='line')

If plotting with pandas is an option, this works:如果可以选择使用pandas绘图,则此方法有效:

df.plot(x= 'depth', layout=(1,2),subplots=True, sharey=True, figsize=(10,4))
plt.show()

Output :输出 在此处输入图片说明

Furthermore, if you would like you can add seaborn styling on top:此外,如果您愿意,可以在顶部添加seaborn样式:

sns.set_style('darkgrid')
df.plot(x= 'depth', layout=(1,2),subplots=True,sharey=True, figsize=(10.5,4))
plt.show()

Output :输出

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM