Python matplotlib颜色栏和直方图(具有共享轴)
我想用Python matplotlib颜色栏和直方图(具有共享轴),python,matplotlib,Python,Matplotlib,我想用imshow显示一个2Dnp.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
imshow
显示一个2Dnp.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_轴(“底部”、“30%”、pad='7%”、sharex=axBar)
,但这会以某种方式改变直方图数据:
除了共享轴x之外,如何修改直方图以采用与颜色贴图相同的颜色,类似于?您可以在不使用sharex的情况下,按bin值为直方图的每个面片上色:
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()
有关更多信息,请查看手册页面:太好了!我通过添加
plt.xlim(data.min(),data.max())
就在N,bin,patches…
行下方解决了共享轴问题。也许您也可以将此添加到答案中。您可以将变体作为新答案发布。