gpt4 book ai didi

python - matplotlib 颜色条和具有共享轴的直方图

转载 作者:行者123 更新时间:2023-12-01 02:42:44 25 4
gpt4 key购买 nike

我想用 imshow 显示 2D np.array 以及相应的颜色条,该颜色条应与 np.array< 的直方图共享其轴。不过,这是一次没有共享轴的尝试。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots(figsize=(7,10))

data = np.random.normal(0, 0.2, size=(100,100))
cax = ax.imshow(data, interpolation='nearest', cmap=cm.jet)

divider = make_axes_locatable(plt.gca())
axBar = divider.append_axes("bottom", '5%', pad='7%')
axHist = divider.append_axes("bottom", '30%', pad='7%')

cbar = plt.colorbar(cax, cax=axBar, orientation='horizontal')
axHist.hist(np.ndarray.flatten(data), bins=50)

plt.show()

我尝试将 axHist 中的 sharex 参数与 axHist =divider.append_axes("bottom", '30%', pad='7% 一起使用', sharex=axBar) 但这会以某种方式改变直方图数据:enter image description here

除了共享轴 x 之外,如何修改直方图以采用与颜色图相同的颜色,类似于 here

最佳答案

您可以按 bin 值对直方图的每个 block 进行着色,而无需使用 sharex:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.colors import Normalize

fig, ax = plt.subplots(figsize=(7,10))

data = np.random.normal(0, 0.2, size=(100,100))
cax = ax.imshow(data, interpolation='nearest', cmap=cm.jet)

divider = make_axes_locatable(plt.gca())
axBar = divider.append_axes("bottom", '5%', pad='7%')
axHist = divider.append_axes("bottom", '30%', pad='7%')

cbar = plt.colorbar(cax, cax=axBar, orientation='horizontal')

# get hist data
N, bins, patches = axHist.hist(np.ndarray.flatten(data), bins=50)

norm = Normalize(bins.min(), bins.max())
# set a color for every bar (patch) according
# to bin value from normalized min-max interval
for bin, patch in zip(bins, patches):
color = cm.jet(norm(bin))
patch.set_facecolor(color)

plt.show()

enter image description here

有关更多信息,请查找手册页:https://matplotlib.org/xkcd/examples/pylab_examples/hist_colormapped.html

关于python - matplotlib 颜色条和具有共享轴的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45504859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com