Mukul Sakhalkar
Mukul Sakhalkar

Reputation: 67

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. I want to keep the depth parameter constant on the x-axis but vary the y-axis parameters as per the other column values.

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

parameter1 vs depth

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

parameter2 vs depth

I have tried to use seaborn.FacetGrid() but I haven't obtained proper results with these.

Let me know how I can plot these graphs as subplots under a single graph without having to define them individually.

Upvotes: 2

Views: 1890

Answers (2)

Grayrigel
Grayrigel

Reputation: 3594

If plotting with pandas is an option, this works:

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

Output: enter image description here

Furthermore, if you would like you can add seaborn styling on top:

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

Output:

enter image description here

Upvotes: 1

Diziet Asahi
Diziet Asahi

Reputation: 40667

To use FacetGrid, you have to transform your dataframe in "long-form" using melt().

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')

enter image description here

Note that the same output can be achieved more simply using relplot instead of creating the FacetGrid "by hand"

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

Upvotes: 3

Related Questions