seaborn在子块中生成单独的数字

2024-04-18 21:16:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在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()

它产生两个独立的图形,而不是一个带有两个子块的图形。为什么它会这样做,为什么seaborn可以被多次调用为单独的子块?

我试图查看下面引用的post,但是我看不到如何添加子块,即使首先调用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()

Tags: 图形dataframepandasdatanppltseaborn子块
1条回答
网友
1楼 · 发布于 2024-04-18 21:16:33

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

下面是一个小技巧,如果您真的想,不管出于什么原因,告诉factorplot要在哪个Axes上执行绘图。正如@mwaskom在评论中指出的那样,这不是一种受支持的行为,因此虽然它现在可能起作用,但将来可能不会起作用。

您可以告诉factorplot使用axkwarg在给定的Axes上绘图,kwarg被传递到matplotlib,因此链接的答案确实可以回答您的查询。但是,由于调用factorplot,它仍将创建第二个图,但该图将为空。在调用plt.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()

enter image description here

相关问题 更多 >