首页 > 解决方案 > 如何绘制共享相同 x 轴的 2 个子图

问题描述

所以目前我有一个scatterplot和一个kdeplot我使用 seaborn 库来绘制的。 这是我绘制图表的方式:. .

# plot a graph to see the zipcodes vs the density
plt.figure(figsize=(16,8))
sns.kdeplot(king['zipcode'], shade=True, legend=False)
plt.xlabel('Zipcode')
plt.ylabel('Density')
plt.figure(figsize=(16,8))
sns.scatterplot(king['zipcode'],king['price'])

但是当我尝试做一个子图时,我的 kdeplot 似乎消失了: . 我试图这样做:

f, axarr = plt.subplots(2, sharex=True)
sns.kdeplot(king['zipcode'], shade=True, legend=False)
sns.scatterplot(king['zipcode'],king['price'])

是否可以在子图中正确渲染两个图形?

标签: python-3.xseaborn

解决方案


是的!感谢@DavidG,我设法正确地绘制了子图。所以我将轴对象添加到各自的图表中。就这样吧。

f, axarr = plt.subplots(2, figsize=(16,8), sharex=True)
sns.kdeplot(king['zipcode'], shade=True, legend=False,ax=axarr[0])
axarr[0].set_ylabel('Density')
sns.scatterplot(x=king['zipcode'],y=king['price'],ax=axarr[1])
plt.show()

结果是: .


推荐阅读