【问题标题】:Setting the size of a matplotlib ColorbarBase object设置 matplotlib ColorbarBase 对象的大小
【发布时间】:2016-10-24 20:47:49
【问题描述】:

我有一个补丁集合,我想为其显示一个颜色图。由于我在颜色图之上进行了一些操作,因此我无法使用 matplotlib.colorbar 实例来定义它。至少据我所知不是;这样做会消除我对颜色所做的一些操作,这些操作会消除缺少数据的补丁:

cmap = matplotlib.cm.YlOrRd
colors = [cmap(n) if pd.notnull(n) else [1,1,1,1]
          for n in plt.Normalize(0, 1)([nullity for _, nullity in squares])]

# Now we draw.
for i, ((min_x, max_x, min_y, max_y), _) in enumerate(squares):
    square = shapely.geometry.Polygon([[min_x, min_y], [max_x, min_y],
                                      [max_x, max_y], [min_x, max_y]])
    ax0.add_patch(descartes.PolygonPatch(square, fc=colors[i], 
                  ec='white', alpha=1, zorder=4))

所以我定义了一个 matplotlib.colorbar.ColorbarBase 实例,它可以工作:

matplotlib.colorbar.ColorbarBase(ax1, cmap=cmap, orientation='vertical',
                                 norm=matplotlib.colors.Normalize(vmin=0, vmax=1))

这会导致例如:

我遇到的问题是我想减小此颜色条的大小(具体而言,将其缩小到特定的垂直大小,例如 500 像素),但我没有看到任何明显的方法。如果我有一个colorbar 实例,我可以使用它的axis property arguments 轻松调整它,但ColorbarBase 缺少这些。

进一步参考:

【问题讨论】:

    标签: python matplotlib colorbar color-mapping


    【解决方案1】:

    大小和形状由轴定义。这是我拥有的代码中的 sn-p,我将 2 个图组合在一起并在顶部独立添加一个颜色条。我使用那个 add_axes 实例中的值,直到我得到一个适合我的大小:

     cax = fig.add_axes([0.125, 0.925, 0.775, 0.0725]) #has to be as a list - starts with x, y coordinates for start and then width and height in % of figure width
     norm = mpl.colors.Normalize(vmin = low_val, vmax = high_val)     
     mpl.colorbar.ColorbarBase(cax, cmap = self.cmap, norm = norm, orientation = 'horizontal')
    

    【讨论】:

    • 颜色条似乎占据了给它的整个axis,因此减小其大小的唯一方法是减小axis 的大小。这确实是最简单的方法。谢谢!
    【解决方案2】:

    这个问题可能有点老了,但我找到了另一个解决方案,它可以帮助那些不愿意为 ColorbarBase 类手动创建颜色条轴的人。

    下面的解决方案使用 matplotlib.colorbar.make_axes 类从给定的轴创建一个依赖的 sub_axes。然后可以为 ColorbarBase 类提供 sub_axes 以创建颜色条。

    代码来源于here中描述的matplotlib代码示例

    这是一个sn-p代码:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import LinearSegmentedColormap
    import matplotlib.colorbar as mcbar
    from matplotlib import ticker
    import matplotlib.colors as mcolors
    
    
    # Make some illustrative fake data:
    
    x = np.arange(0, np.pi, 0.1)
    y = np.arange(0, 2 * np.pi, 0.1)
    X, Y = np.meshgrid(x, y)
    Z = np.cos(X) * np.sin(Y) * 10
    
    
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]  # R -> G -> B
    
    n_bins = [3, 6, 10, 100]  # Discretizes the interpolation into bins
    
    cmap_name = 'my_list'
    
    
    fig, axs = plt.subplots(2, 2, figsize=(9, 7))
    fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
    for n_bin, ax in zip(n_bins, axs.ravel()):
        # Create the colormap
        cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bin)
        # Fewer bins will result in "coarser" colomap interpolation
        im = ax.imshow(Z, interpolation='nearest', origin='lower', cmap=cm)
        ax.set_title("N bins: %s" % n_bin)
    
        cax, cbar_kwds = mcbar.make_axes(ax, location = 'right',
                                  fraction=0.15, shrink=0.5, aspect=20)
    
    
    
    
        cbar = mcbar.ColorbarBase(cax, cmap=cm, 
                                  norm=mcolors.Normalize(clip=False), 
                                  alpha=None, 
                                  values=None, 
                                  boundaries=None, 
                            orientation='vertical', ticklocation='auto', extend='both', 
                            ticks=n_bins, 
                            format=ticker.FormatStrFormatter('%.2f'), 
                            drawedges=False, 
                            filled=True, 
                            extendfrac=None, 
                            extendrect=False, label='my label')
    
    
    
    
        if n_bin <= 10:
            cbar.locator = ticker.MaxNLocator(n_bin) 
            cbar.update_ticks()
    
        else:
            cbar.locator = ticker.MaxNLocator(5) 
            cbar.update_ticks()
    
    
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      相关资源
      最近更新 更多