Seborn未在定义的子图内绘制 [英] seaborn is not plotting within defined subplots

查看:19
本文介绍了Seborn未在定义的子图内绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此代码并排绘制两个布局

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)

它返回以下结果(两个空子图,后跟两行一分图)-

如果我用ViinPlot尝试相同的代码,它会按预期返回结果

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的文档,已在seaborn 0.11DEPRECATED
  • .distplot替换为:
    • displot(),这是一个图形级函数,对于要绘制的绘图类型具有类似的灵活性。这是FacetGrid,没有ax参数。
    • histplot(),用于绘制直方图的轴级函数,包括内核密度平滑。它确实有ax参数。
  • 适用于没有ax参数的任何seabornFacetGrid曲线图。使用等效的轴级图。
    • 查看图形级别绘图的文档,查找适合您需要的轴级绘图函数。
  • 因为需要两个不同列的直方图,所以更容易使用histplot
  • 有关绘制到maplotlib.pyplot.subplots的多种不同方式,请参阅How to plot in multiple subplots
  • seaborn 0.11.1&;matplotlib 3.4.2
  • 中测试
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)

导入和DataFrame示例

import seaborn as sns
import matplotlib.pyplot as plt

# 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

轴级别图

  • 如果数据格式较宽,请使用sns.histplot
# select the columns to be plotted
cols = ['bill_length_mm', 'bill_depth_mm']

# create the figure and axes
fig, axes = plt.subplots(1, 2)
axes = axes.ravel()  # flattening the array makes indexing easier

for col, ax in zip(cols, axes):
    sns.histplot(data=penguins[col], kde=True, stat='density', ax=ax)

fig.tight_layout()
plt.show()

图形级别图

  • 对于长格式的数据帧,请使用displot
# create a long dataframe
dfl = penguins.melt(id_vars='species', value_vars=['bill_length_mm', 'bill_depth_mm'], var_name='bill_size', value_name='vals')

# display(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', kde=True, stat='density', common_bins=False, common_norm=False, height=4, facet_kws={'sharey': False, 'sharex': False})

这篇关于Seborn未在定义的子图内绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆