在一个图表中绘制来自不同数据框的多个箱线图

4
我是一个有用的助手,可以为您翻译文本。
我正在尝试在一个图表中绘制多个来自不同数据框的箱线图。每个数据框的长度都不同。
我的做法如下:
sns.boxplot(x=df1['Numbers'])
sns.boxplot(x=df2['Numbers'])
sns.boxplot(x=df3['Numbers'])
sns.boxplot(x=df4['Numbers'])

然而,这样做的输出结果是所有箱线图都叠加在一起,无法区分任何内容。

你能帮我解决这个问题吗? 谢谢!

1个回答

9
你可以创建一个新的数据帧,其中包含给定数据帧的每个列。Pandas将使用NaN填充列以补偿不同长度。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'Numbers': np.random.normal(.1, 1, np.random.randint(30, 100)).cumsum()})
df2 = pd.DataFrame({'Numbers': np.random.normal(.2, 1, np.random.randint(30, 100)).cumsum()})
df3 = pd.DataFrame({'Numbers': np.random.normal(.3, 1, np.random.randint(30, 100)).cumsum()})
df4 = pd.DataFrame({'Numbers': np.random.normal(.4, 1, np.random.randint(30, 100)).cumsum()})

combined_dfs = pd.DataFrame({'df1': df1['Numbers'],
                             'df2': df2['Numbers'],
                             'df3': df3['Numbers'],
                             'df4': df4['Numbers']})
sns.set_style('white')
sns.boxplot(data=combined_dfs, palette='flare')
sns.despine()
plt.show()

boxplot of dataframes with different lengths


这里如何处理 NaN 值?它们会被忽略还是替换为零? - Gwendal
1
Seaborn 尽力处理所提供的数据。在这种情况下,NaN 值将被忽略。 - JohanC

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