Python 带有单个数据点的pyplot条形图
我有来自对照组和治疗组的数据。matplotlib是否能够创建条形图,其中条形图高度为每个组的平均值,并与该组中的各个数据点重叠?我想可视化实际数据点的分布,类似于显示的内容Python 带有单个数据点的pyplot条形图,python,matplotlib,Python,Matplotlib,我有来自对照组和治疗组的数据。matplotlib是否能够创建条形图,其中条形图高度为每个组的平均值,并与该组中的各个数据点重叠?我想可视化实际数据点的分布,类似于显示的内容 我曾考虑过使用箱线图和散点图的组合,但我的尝试没有成功。这里有一个解决方案正是按照您提到的那样:用散点图覆盖条形图 当然,您可以进一步调整绘图:绘图标题、轴标签、颜色、宽度、散点图的标记形状 import matplotlib.pyplot as plt np.random.seed(123) w = 0.8 #
我曾考虑过使用箱线图和散点图的组合,但我的尝试没有成功。这里有一个解决方案正是按照您提到的那样:用散点图覆盖条形图 当然,您可以进一步调整绘图:绘图标题、轴标签、颜色、宽度、散点图的标记形状
import matplotlib.pyplot as plt
np.random.seed(123)
w = 0.8 # bar width
x = [1, 2] # x-coordinates of your bars
colors = [(0, 0, 1, 1), (1, 0, 0, 1)] # corresponding colors
y = [np.random.random(30) * 2 + 5, # data series
np.random.random(10) * 3 + 8]
fig, ax = plt.subplots()
ax.bar(x,
height=[np.mean(yi) for yi in y],
yerr=[np.std(yi) for yi in y], # error bars
capsize=12, # error bar cap width in points
width=w, # bar width
tick_label=["control", "test"],
color=(0,0,0,0), # face color transparent
edgecolor=colors,
#ecolor=colors, # error bar colors; setting this raises an error for whatever reason.
)
for i in range(len(x)):
# distribute scatter randomly across whole width of bar
ax.scatter(x[i] + np.random.random(y[i].size) * w - w / 2, y[i], color=colors[i])
plt.show()
它将产生这个图表
这里有一个使用Seaborn的解决方案,它提供了更短的代码,但与直接使用Matplotlib相比,它放弃了一些灵活性:
import seaborn as sns, matplotlib.pyplot as plt
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
sns.barplot(x="day", y="total_bill", data=tips, capsize=.1, ci="sd")
sns.swarmplot(x="day", y="total_bill", data=tips, color="0", alpha=.35)
plt.show()
结果如下: