Seaborn在定义的子图中无法绘图。

29
我正在尝试使用这段代码并排绘制两个displots
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)
它返回以下结果(两个空子图,然后是两行中的一个displot)- enter image description here enter image description here enter image description here 如果我使用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为什么会返回不同类型的输出,我该如何在同一行输出两个图形?

1个回答

41
  • seaborn.distplotseaborn 0.11中已被弃用,并被以下函数替代:
    • displot(),一个图形级别的函数,具有类似的绘图类型的灵活性。这是一个FacetGrid,没有ax参数,所以它不能与matplotlib.pyplot.subplots一起使用
    • histplot(),一个轴级别的函数,用于绘制直方图,包括核密度平滑。它有ax参数,所以可以与matplotlib.pyplot.subplots一起使用
  • 对于任何没有ax参数的seaborn FacetGrid绘图,都可以使用相应的轴级别绘图。
  • 因为需要绘制两个不同列的直方图,所以使用histplot更容易。
  • 参见如何在多个子图中绘制,了解在maplotlib.pyplot.subplots中绘制的多种不同方法。
  • 还请查看seaborn histplot和displot输出不匹配
  • seaborn 0.11.1matplotlib 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

坐标轴级别绘图

# 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()

enter image description here

图表级别绘图

  • 使用长格式的数据框,使用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})

多个数据框

  • 如果有多个数据框,可以使用pd.concat将它们合并,并使用.assign创建一个标识性的'source'列,该列可以用于row=col=hue=
# list of dataframe
lod = [df1, df2, df3]

# create one dataframe with a new 'source' column to use for row, col, or hue
df = pd.concat((d.assign(source=f'df{i}') for i, d in enumerate(lod, 1)), ignore_index=True)

请参考将多个csv文件导入pandas并合并为一个DataFrame,以了解如何将多个文件读入单个数据框,并添加一个标识列。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接