Plot multiple DataFrame columns in Seaborn FacetGrid

别说谁变了你拦得住时间么 提交于 2019-12-21 04:21:15

问题


I am using the following code

import seaborn as sns

g = sns.FacetGrid(dataframe, col='A', hue='A')
g.map(plt.plot, 'X', 'Y1')
plt.show()

to make a seaborn facet plot like this:

Now I would like to add another row to this plot with a different variable, call it Y2, on the y axis. The result should look similar to vertically stacking the two plots obtained by

g = sns.FacetGrid(dataframe, col='A', hue='A')
g.map(plt.plot, 'X', 'Y1')
plt.show()

g = sns.FacetGrid(dataframe, col='A', hue='A')
g.map(plt.plot, 'X', 'Y2')
plt.show()

but in a single plot, without the duplicate x axis and titles ("A=<value>") and without creating a new FacetGrid object.

Note that

g = sns.FacetGrid(dataframe, col='A', hue='A')
g.map(plt.plot, 'X', 'Y1')
g.map(plt.plot, 'X', 'Y2')
plt.show()

does not achive this, because it results in both the curve for Y1 and Y2 being displayed in the same subplot for each value of A.


回答1:


I used the following code to create a synthetic dataset which appears to match yours:

import pandas
import numpy
import seaborn as sns
import matplotlib.pyplot as plt

# Generate synthetic data
omega = numpy.linspace(0, 50)

A0s = [1., 18., 40., 100.]

dfs = []
for A0 in A0s:
    V_w_dr = numpy.sin(A0*omega)
    V_w_tr = numpy.cos(A0*omega)
    dfs.append(pandas.DataFrame({'omega': omega,
                                 'V_w_dr': V_w_dr,
                                 'V_w_tr': V_w_tr,
                                 'A0': A0}))
dataframe = pandas.concat(dfs, axis=0)

Then you can do what you want (thanks to @mwaskom in the comments for )sharey='row', margin_titles=True):

melted = dataframe.melt(id_vars=['A0', 'omega'], value_vars=['V_w_dr', 'V_w_tr'])
g = sns.FacetGrid(melted, col='A0', hue='A0', row='variable', sharey='row', margin_titles=True)
g.map(plt.plot, 'omega', 'value')

This results in



来源:https://stackoverflow.com/questions/30623721/plot-multiple-dataframe-columns-in-seaborn-facetgrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!