首页 > 解决方案 > 在 hist 和 hist2d 的子图中将颜色条放在特定 hist2d 上

问题描述

我已经看到了一些使用 ImageGrid 的建议(比如这里),但我的问题是这些都是 hist2d 也没有不同类型的图。也许解决方案对某些人来说是显而易见的,但是当并非所有其他子图都是 hist2d 时,我不确定如何在特定的 ax 中专门显示 hist2d 的颜色图。

这是我正在尝试做的一个示例,其中包含随机生成的数据。标题等基于我的实际数据,但出于本演示的目的,您可以忽略这些。

这是示例代码:

# imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# seed random number
np.random.seed(0)

# random normally distributed data
entries = 100000
# first signal
mu1, sigma1 = 0.5, 0.01 # mean and standard deviation
s1 = np.random.normal(mu1, sigma1, entries)
# second signal
mu2, sigma2 = 0.45, 0.02 # mean and standard deviation
s2 = np.random.normal(mu2, sigma2, entries)

# fig and ax
fig, ax = plt.subplots(2, 3, figsize = (30, 15))

# fill plots
ax[0, 0].hist(s1, bins = 100, density = True, range = (0.45, 0.55))
# log scale for z axis
ax[0, 1].hist2d(s2, s1, bins = 100, range = ((0.35, 0.55), (0.45, 0.55)), norm = mpl.colors.LogNorm(), cmap = "plasma")
ax[0, 2].hist(s2, bins = 100, density = True, range = (0.35, 0.55))

ax[1, 0].hist(s1, bins = 100, density=True, range = (0.45, 0.55))
# log scale for z axis
ax[1, 1].hist2d(s2, s1, bins = 100, range = ((0.35, 0.55), (0.45, 0.55)), norm = mpl.colors.LogNorm(), cmap = "plasma")
ax[1, 2].hist(s2, bins = 100, density = True, range = (0.35, 0.55))

# plot settings (titles, etc)
for i in range(0,2):
    for j in range(0,3):
        if i == 0:
            ax[i, j].set_title(r"proton in FD", fontsize = 22)
        elif i == 1:
            ax[i, j].set_title(r"proton in CD", fontsize = 22)
        ax[i, j].grid(color = 'black', linestyle = ':', linewidth = 0.5, zorder = 0)
        ax[i, j].ticklabel_format(axis = "y", style = "sci", scilimits = (0,0))

        # axis names
        if j == 0:
            ax[i, j].set(xlabel = "MM$^2$ [GeV$^2$]")
            ax[i, j].set(ylabel = "Count")
        if j == 1:
            ax[i, j].set(xlabel = "IM($2\gamma$) [GeV]")
            ax[i, j].set(ylabel = "MM$^2$ [GeV$^2$]")
        if j == 2:
            ax[i, j].set(xlabel = "IM($2\gamma$) [GeV]")
            ax[i, j].set(ylabel = "Count")

fig.suptitle("final states: full data skim $ep\gamma$ + any additional particles", fontsize=25)
plt.show()

这是我从上述代码中得到的输出:

在此处输入图像描述

我想做的是为两个 hist2d 图像放置颜色条,但是当我尝试执行 ax[0,1].colorbar() 之类的操作时,我遇到了 ax 没有颜色条的问题。我将不得不使用 fig.colorbar() 或 plt.colorbar() 并且我不确定如何使用它来显示特定的子图。

有没有办法做到这一点?感谢您的帮助。

标签: pythonmatplotlibhistogramsubplotcolorbar

解决方案


推荐阅读