我需要并排绘制两个图形。这是我感兴趣的数据集中的列。
X
1
53
12
513
135
125
21
54
1231
我做到了
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
mean = df['X'].mean()
fig, ax =plt.subplots(1,2)
sns.displot(df, x="X", kind="kde", ax=ax[0]) # 1st plot
plt.axvline(mean, color='r', linestyle='--') # this add just a line on the previous plot, corresponding to the mean of X data
sns.boxplot(y="X", data=df, ax=ax[2]) # 2nd plot
但我有这个错误:IndexError: index 2 is out of bounds for axis 0 with size 2
,所以使用子图是错误的。
答案 0 :(得分:2)
sns.boxplot(..., ax=ax[2])
应该使用 ax=ax[1]
,因为不存在 ax[2]
。
sns.displot
是一个 figure-level function,它创建自己的图形,并且不接受 ax=
参数。如果只需要一个子图,可以用sns.histplot
或sns.kdeplot
代替。
plt.axvline()
借鉴“当前”ax
。您可以使用 ax[0].axvline()
在特定的子图上绘制。见What is the difference between drawing plots using plot, axes or figure in matplotlib?
以下代码已使用 Seaborn 0.11.1 进行测试:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
sns.set()
df = pd.DataFrame({'X': [1, 53, 12, 513, 135, 125, 21, 54, 1231]})
mean = df['X'].mean()
fig, ax = plt.subplots(1, 2)
sns.kdeplot(data=df, x="X", ax=ax[0])
ax[0].axvline(mean, color='r', linestyle='--')
sns.boxplot(y="X", data=df, ax=ax[1])
plt.show()