seaborn 未在定义的子图内绘图
- 2025-01-13 08:52:00
- admin 原创
- 97
问题描述:
我正在尝试用此代码并排绘制两个图
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 返回不同类型的输出以及我该怎么做才能在同一行输出两个图?
解决方案 1:
seaborn.distplot
已被DEPRECATED
替换seaborn 0.11
为以下内容:displot()
,一个图形级函数,对要绘制的图类型具有类似的灵活性。这是一个FacetGrid
,并且没有ax
参数,因此它不能与 一起使用matplotlib.pyplot.subplots
。histplot()
,用于绘制直方图的轴级函数,包括核密度平滑。它确实有ax
参数,因此可以与一起使用matplotlib.pyplot.subplots
。
它适用于任何
seaborn
FacetGrid
没有ax
参数的图。使用等效的轴级图。查看图形级绘图的文档以找到适合您需要的轴级绘图函数。
参见图形级与轴级函数
图形级别:
relplot
,,displot
`catplot`
因为需要两列不同数据的直方图,所以使用起来比较方便
histplot
。请参阅如何绘制多个子图,了解绘制子图的多种不同方法
maplotlib.pyplot.subplots
还请查看seaborn histplot 和 displot 输出不匹配
在
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
.ravel
、、.flatten
都将数组.flat
转换axes
为一维。numpy 中的 flatten 和 ravel 函数有什么区别?
numpy flat 和 ravel() 之间的区别
绘制子图时如何修复“numpy.ndarray”对象没有属性“get_figure”
# 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})
多个 DataFrame
如果有多个数据框,它们可以与 组合
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,以将多个文件读入具有标识列的单个数据框。