pandas 在 Seaborn FacetGrid 中绘制多个 DataFrame 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30623721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:25:35  来源:igfitidea点击:

Plot multiple DataFrame columns in Seaborn FacetGrid

pythonpandasmatplotlibplotseaborn

提问by arccos

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: Example facet plot

制作这样的 seaborn 分面图: 示例分面图

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

现在我想用不同的变量向该图中添加另一行,在 y 轴上将其命名为 Y2。结果应该类似于垂直堆叠通过以下方式获得的两个图

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

Example plot with two rows

两行示例图

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

但在单个图中,没有重复的 x 轴和标题(“A=<value>”),也没有创建新FacetGrid对象。

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.

没有实现这一点,因为它导致 Y1 和 Y2 的曲线对于 A 的每个值都显示在同一个子图中。

采纳答案by chthonicdaemon

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

然后你可以做你想做的事(感谢@mwaskom 在评论中)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

这导致

Result of plotting melted data

绘制融化数据的结果