seaborn在次要情节中产生单独的数字

lgd*_*lgd 11 python matplotlib seaborn

我正试图在seaborn中使用以下方法制作2x1子情节图:

data = pandas.DataFrame({"x": [1, 2, 4],
                        "y": [10,20,40],
                        "s": [0.01,0.1,1.0]})

plt.figure()
plt.subplot(2, 1, 1)
sns.pointplot(x="x", y="y", data=data)
plt.errorbar(np.arange(len(data["x"])), data["y"], yerr=data["s"])
plt.subplot(2, 1, 2)
sns.factorplot(x="x", y="y", data=data)
plt.show()
Run Code Online (Sandbox Code Playgroud)

它产生两个独立的数字,而不是一个带有两个子图的单个数字.为什么它会这样做?如何为多个单独的子图调用seaborn?

我试着查看下面引用的帖子,但我看不到即使factorplot首先调用也可以添加子图.有人能举例说明吗?这会有所帮助.我的尝试:

data = pandas.DataFrame({"x": [1, 2, 4],
                        "y": [10,20,40],
                        "s": [0.01,0.1,1.0]})

fig = plt.figure()
sns.pointplot(x="x", y="y", data=data)
ax = sns.factorplot(x="x", y="y", data=data)
fig.add_subplot(212, axes=ax)
plt.errorbar(np.arange(len(data["x"])), data["y"], yerr=data["s"])
plt.show()
Run Code Online (Sandbox Code Playgroud)

tmd*_*son 15

问题是factorplot创建一个新FacetGrid实例(反过来创建自己的图形),它将应用绘图函数(默认情况下为pointplot).因此,如果您想要的只是pointplot,那么使用它是有意义的pointplot,而不是factorplot.

以下是一个黑客,如果你真的想,无论出于何种原因,告诉factorplotAxes执行其密谋.正如@mwaskom在评论中指出的那样,这不是受支持的行为,因此虽然它现在可能有效,但未来可能不会.

你可以告诉你使用kwarg factorplot对给定的情节进行绘图,然后传递给你,因此链接的答案可以回答你的问题.但是,由于调用,它仍然会创建第二个数字,但这个数字只是空的.这里有一个解决方法,它可以在调用前关闭那个额外的数字Axesaxmatplotlibfactorplotplt.show()

例如:

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

data = pandas.DataFrame({"x": [1, 2, 4],
                        "y": [10,20,40],
                        "s": [10,10,10]}) # I increased your errors so I could see them

# Create a figure instance, and the two subplots
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Tell pointplot to plot on ax1 with the ax argument
sns.pointplot(x="x", y="y", data=data, ax=ax1)

# Plot the errorbar directly on ax1
ax1.errorbar(np.arange(len(data["x"])), data["y"], yerr=data["s"])

# Tell the factorplot to plot on ax2 with the ax argument
# Also store the FacetGrid in 'g'
g=sns.factorplot(x="x", y="y", data=data, ax=ax2)

# Close the FacetGrid figure which we don't need (g.fig)
plt.close(g.fig)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 有一个根本的混乱.`factorplot`只是将一个绘图函数(默认为`pointplot`)应用到由`FacetGrid`管理的子图网格上.尝试将`factorplot`绘制到现有的子图上是没有意义的.只需使用`pointplot`. (3认同)
  • 这个"有效",因为`factorplot`通过它的kwargs,所以`ax`参数到达正确的位置,但是这种特殊的行为不受支持,我不会依赖它. (2认同)
  • 我真的不确定你的意思.在一个子图中,没有什么`factorplot`确实'pointplot`没有做,因为`factorplot`实际上只是在每个轴上调用`pointplot`. (2认同)