设置 matplotlib ColorbarBase 对象的大小

Setting the size of a matplotlib ColorbarBase object

我有一个补丁集,我想为其显示一个颜色贴图。由于我在颜色图上进行了一些操作,因此我无法使用 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 缺少这些。

进一步参考:

尺寸和形状用轴定义。这是我拥有的代码片段,我将 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')

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

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

代码源自here

中描述的matplotlib代码示例

这是一段代码:

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()