Matplotlib 叠加双峰直方图
Posted
技术标签:
【中文标题】Matplotlib 叠加双峰直方图【英文标题】:Matplotlib overlay bimodal histograms 【发布时间】:2021-12-20 17:11:33 【问题描述】:我试图将三个“双峰/二元直方图”放在同一个图上,标记为实际值而不是 bin。不确定这是否有意义...但是,我想显示每个向量 x1、x2 和 x3 中仅有的 2 个值。
代码如下:
import matplotlib.pyplot as plt
x1 = [0.003996747444034554, 0.003996747444034554, 0.003996747458586469, 0.003996747444034554, 0.003996747444034554, 0.003996747444034554, 0.003996747458586469, 0.003996747444034554, 0.003996747444034554, 0.003996747444034554]
x2 = [0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536310296506, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845]
x3 = [0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643761638552, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891]
fig, axs = plt.subplots(1,3, figsize=([7,4]), sharey = True)
axs[0].hist(x1)
axs[1].hist(x2)
axs[2].hist(x3)
plt.tight_layout()
plt.figure(figsize=([7,4]))
plt.hist([x1,x2,x3])
图 1 是每个直方图(x1、x2 和 x3)的图:
图 2 是一次绘制的结果:
【问题讨论】:
您的 3 个数组不相交,我不知道如何修改您的绘图。 【参考方案1】:每个向量内的差异远小于向量均值之间的差异,因此每个向量的两个直方图条都重合。 对于这种特殊情况,您可以改用stem plot:
import matplotlib.pyplot as plt
import pandas as pd
x1 = [0.003996747444034554, 0.003996747444034554, 0.003996747458586469, 0.003996747444034554, 0.003996747444034554, 0.003996747444034554, 0.003996747458586469, 0.003996747444034554, 0.003996747444034554, 0.003996747444034554]
x2 = [0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536310296506, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845, 0.003996536252088845]
x3 = [0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643761638552, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891, 0.003996643703430891]
g1 = pd.Series(x1).groupby(x1).count()
plt.stem(g1.index, g1.values, markerfmt='C0o', linefmt='C0-')
g2 = pd.Series(x2).groupby(x2).count()
plt.stem(g2.index, g2.values, markerfmt='C1o', linefmt='C1-')
g3 = pd.Series(x3).groupby(x3).count()
plt.stem(g3.index, g3.values, markerfmt='C2o', linefmt='C2-')
(您需要放大才能看到每个向量的两个 x 位置之间的差异)
【讨论】:
以上是关于Matplotlib 叠加双峰直方图的主要内容,如果未能解决你的问题,请参考以下文章
python matplotlib画的直方图怎么加两条竖线做参考线
Python中Pandas/Matplotlib中直方图和密度的叠加