我有以下数据框和下面的图 - 我想为因子图中的每个箱形图添加数据点,但我在将箱形图和条形图组合到同一个图中时遇到问题(即它们不重叠,它们出现在下面)彼此)。有解决办法吗?
import pandas as pd
import datetime
idx = pd.date_range('01-01-2020', '01-25-2020')
d = pd.Series({'01-01-2020': 1,
'01-25-2020': 1})
d.index = pd.DatetimeIndex(d.index)
d = d.reindex(idx, fill_value=0)
df = pd.DataFrame(d).rename_axis("dt").reset_index()
df.drop(columns=df.columns[1], inplace=True)
# calculate week number
df["week"] = df["dt"].dt.week
# create column counts for 'nhsbt centres'
df["A"] = np.random.randint(0, 50, df.shape[0])
df["B"] = np.random.randint(0, 30, df.shape[0])
df["C"] = np.random.randint(0, 20, df.shape[0])
# melt dataframe
df1 = df[["A", "B", "C", "week"]]
df1 = df1.set_index("week")
df1 = df1.melt(ignore_index=False)
df1["week"] = df1.index
# make boxplot
sns.factorplot("week", "value", col="variable", data=df1, kind="box")
最佳答案
- 将轴级图添加到图形级图上的最清晰方法,例如
seaborn.catplot
,就是使用.map
,如seaborn: Building structured multi-plot grids所示 -
seaborn.factorplot
更名为.catplot
但是,如果您使用的是旧版本的seaborn
,.map
应该仍然有效。 -
.dt.week
已弃用,应替换为.dt.isocalendar().week
- 测试于
pandas 1.3.2
,seaborn 0.11.2
和matplotlib 3.4.3
import seaborn as sns
# make boxplot with data from the OP
g = sns.catplot(x="week", y="value", col="variable", data=df1, kind="box")
g.map(sns.swarmplot, 'week', 'value', color='k', order=sorted(df1.week.unique()))
关于python - 如何在seaborn图形级箱线图上叠加数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68950379/