繁体   English   中英

并排绘制两个图(seaborn 和子图)

[英]Plotting two graphs side by side (seaborn and subplots)

我需要 plot 两个并排的图。 这是我感兴趣的数据集中的列。

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 ,所以使用子图是错误的。

sns.boxplot(..., ax=ax[2])应该使用ax=ax[1]因为不存在ax[2]

sns.displot图形级别的 function ,它创建自己的图形,并且不接受ax=参数。 如果只需要一个子图,可以将其替换为sns.histplotsns.kdeplot

plt.axvline()使用“当前” ax 您可以使用ax[0].axvline()在特定的子图上绘图。 请参阅matplotlib 中使用 plot、轴或图形绘制图有什么区别?

以下代码已使用 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()

seaborn kdeplot 和箱线图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM