[英]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)
sns.relplot(x='depth',y="parameter2",kind='line',data=df)
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()
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.