具有共享轴

时间:2017-08-04 10:47:47

标签: python matplotlib

我想显示带有np.array的2D imshow和相应的颜色条,它们应该与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()

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用bin值为每个直方图补丁而不使用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