我正在尝试与此代码并排绘制两个缺陷
fig,(ax1,ax2) = plt.subplots(1,2)
sns.displot(x =X_train['Age'], hue=y_train, ax=ax1)
sns.displot(x =X_train['Fare'], hue=y_train, ax=ax2)
它返回以下结果(两个空子图,然后在两行中各显示一个图)-如果我用violinplot尝试相同的代码,它会按预期返回结果
fig,(ax1,ax2) = plt.subplots(1,2)
sns.violinplot(y_train, X_train['Age'], ax=ax1)
sns.violinplot(y_train, X_train['Fare'], ax=ax2)
为什么Displot返回不同类型的输出,我该怎么做才能在同一行上输出两个图?
最佳答案
seaborn.distplot
的文档,该文档在DEPRECATED
中为seaborn 0.11
。 .distplot
被替换为以下内容:displot()
,一种图形级别的函数,与要绘制的绘图类似,具有类似的灵活性。这是 FacetGrid
,没有ax
参数。 histplot()
,一种轴级函数,用于绘制直方图,包括内核密度平滑处理。它确实具有ax
参数。 histplot
更容易。 fig,(ax1,ax2) = plt.subplots(1,2)
sns.histplot(x=X_train['Age'], hue=y_train, ax=ax1)
sns.histplot(x=X_train['Fare'], hue=y_train, ax=ax2)
例子sns.histplot
import seaborn as sns
# load data
penguins = sns.load_dataset("penguins", cache=False)
# display(penguins.head())
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
0 Adelie Torgersen 39.1 18.7 181.0 3750.0 MALE
1 Adelie Torgersen 39.5 17.4 186.0 3800.0 FEMALE
2 Adelie Torgersen 40.3 18.0 195.0 3250.0 FEMALE
3 Adelie Torgersen NaN NaN NaN NaN NaN
4 Adelie Torgersen 36.7 19.3 193.0 3450.0 FEMALE
# set x and y
x, y = penguins.bill_length_mm, penguins.bill_depth_mm
# plot
fig, (ax1, ax2) = plt.subplots(1, 2)
sns.histplot(x, kde=True, ax=ax1)
sns.histplot(y, kde=True, ax=ax2)
plt.tight_layout()
displot
# create a long dataframe
dfl = pd.DataFrame(penguins[['species', 'bill_length_mm', 'bill_depth_mm']].set_index('species').stack()).reset_index().rename(columns={'level_1': 'bill_size', 0: 'vals'})
# disply(dfl.head())
species bill_size vals
0 Adelie bill_length_mm 39.1
1 Adelie bill_depth_mm 18.7
2 Adelie bill_length_mm 39.5
3 Adelie bill_depth_mm 17.4
4 Adelie bill_length_mm 40.3
# plot
sns.displot(data=dfl, x='vals', col='bill_size', kind='hist', kde=True)
关于python - seaborn displot()未在定义的子图中绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63895392/