【问题标题】:matplotlib colorbar and histogram with shared axismatplotlib 颜色条和直方图与共享轴
【发布时间】:2017-08-04 10:47:47
【问题描述】:

我想显示一个带有imshow 的二维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) 一起使用,但这会以某种方式改变直方图数据:

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以在不使用 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()
    

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

    【讨论】:

    • 太棒了!我通过在N, bins, patches ... 行下方添加plt.xlim(data.min(), data.max()) 解决了共享轴问题也许您也可以将其添加到答案中。
    • 您可以发布您的变体作为新答案。
    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2020-01-05
    • 2016-08-14
    相关资源
    最近更新 更多