如何用x y叠加覆盖多个直方图

时间:2018-12-20 04:15:30

标签: python matplotlib histogram

我正在尝试覆盖多个直方图,并在x y轴上移动每个直方图。到目前为止,我正在生成单个图并使用illustrator设计最终图,但是我想在脚本中完成所有操作。尝试了很长时间,但没有成功。我准备了一个小案子。这个数据集没有多大意义,但是对于我的数据来说,这是一个很好的解决方案。如果有人可以帮助,我将非常高兴。 谢谢

这是生成重叠直方图的示例代码。

import random
import numpy
import matplotlib.pyplot as plt
%matplotlib inline

data1 = [random.gauss(3,2) for _ in range(400)]
data2 = [random.gauss(4,2) for _ in range(400)]
data3 = [random.gauss(5,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

plt.xlim(0, 10)
plt.ylim(0, 25)

plt.hist(data3, bins, label='data3')
plt.hist(data2, bins, label='data2')
plt.hist(data1, bins, label='data1')
plt.legend(loc='upper right')
plt.savefig("trial01.pdf", transparent=True)

Overlaid Histograms

但是我想要的数字与此相似

Expected Histogram Figure

1 个答案:

答案 0 :(得分:1)

您可能想移动整个轴及其内容。这将需要在其自己的轴上绘制每个直方图,共享轴,并设置各自的轴位置(ax.set_position)。然后,您可以在需要的地方关闭刻度线,刺和标签。

import random
import numpy
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

data1 = [random.gauss(3,2) for _ in range(400)]
data2 = [random.gauss(4,2) for _ in range(400)]
data3 = [random.gauss(5,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

fig, ax1 = plt.subplots()

ax2 = fig.add_subplot(111, sharex=ax1, sharey=ax1, label="ax2")
ax3 = fig.add_subplot(111, sharex=ax1, sharey=ax1, label="ax3")

ax1.set(xlim=(0, 10), ylim=(0, 25))

ax1.hist(data3, bins, label='data3', color="C2")
ax2.hist(data2, bins, label='data2', color="C1")
ax3.hist(data1, bins, label='data1', color="C0")
fig.legend(loc='upper right')


xshift=0.04; yshift=0.04
for i, ax in enumerate((ax3,ax2,ax1)):
    ax.patch.set_visible(False)
    pos = ax.get_position()
    newpos = Bbox.from_bounds(pos.x0+i*xshift, pos.y0+i*yshift, pos.width, pos.height)
    ax.set_position(newpos)
    for sp in ["top", "right"]:
        ax.spines[sp].set_visible(False)

    if ax != ax3:
        ax.spines["left"].set_visible(False)
        ax.tick_params(labelleft=False, left=False, labelbottom=False)

fig.savefig("trial01.pdf", transparent=True)
plt.show()

enter image description here