Matplotlib - 两个问题:共享色条/标签不显示

1 投票
2 回答
2920 浏览
提问于 2025-04-18 02:51

我终于把我想要的三个图放到一个图里,做成了三个子图……现在我需要加一个公共的颜色条,最好是横着的。而且,因为我把它们做成了子图,之前的标签也没了。

看起来例子里建议我 添加一个坐标轴,但我不太明白参数里的数字是什么意思。

def plot_that_2(x_vals, y_vals, z_1_vals, z_2_vals, z_3_vals, figname, units, efficiency_or_not):
    global letter_pic_width    
    plt.close()    #I moved this up from the end of the file because it solved my QTagg problem
    UI = [uniformity_calc(z_1_vals), uniformity_calc(z_2_vals), uniformity_calc(z_3_vals)]
    ranges = [ str(int(np.max(z_1_vals) - np.min(z_1_vals))), str(int(np.max(z_2_vals) - np.min(z_2_vals))), str(int(np.max(z_3_vals) - np.min(z_3_vals)))]
    z_vals = [z_1_vals, z_2_vals, z_3_vals]

    fig = plt.figure(figsize = (letter_pic_width, letter_pic_width/3 ))
    ax0 = fig.add_subplot(1,3,1, aspect = 1)
    ax1 = fig.add_subplot(1,3,2, aspect = 1)
    ax2 = fig.add_subplot(1,3,3, aspect = 1)

    axenames = [ax0, ax1, ax2]

    for z_val, unif, rangenum, ax in zip(z_vals, UI, ranges, axenames):
        ax.scatter(x_vals, y_vals, c = z_val, s = 100, cmap = 'rainbow')
        if efficiency_or_not:
            ax.vmin = 0
            ax.vmax = 1
            ax.xlabel = 'Uniformity: ' + unif
        else:
            ax.xlabel = 'Uniformity: ' + unif + '   ' + rangenum + ' ppm'

    plt.savefig('./'+ figname + '.jpg', dpi = 100) 

这是当效率 = True 时的图。我觉得它也没有设置 vmin / vmax。

2 个回答

2

关于你问的颜色条轴,数字代表的是

[bottom_left_x_coord, bottom_left_y_coord, width, height]

一个合适的颜色条可能是

# x    y    w     h
[0.2, 0.1, 0.6, 0.05]

这是你的代码,稍微修改了一下,增加了颜色条:

import numpy as np
import matplotlib.pyplot as plt

WIDTH = 9

def uniformity_calc(x):
    return x.mean()

def plotter(x, y, zs, name, units, efficiency=True):
    fig, axarr = plt.subplots(1, 3, figsize=(WIDTH, WIDTH/3), 
                              subplot_kw={'aspect':1})
    fig.suptitle(name)

    UI = map(uniformity_calc, zs)
    ranges = map(lambda x: int(np.max(x)-np.min(x)), zs)

    for ax, z, unif, rangenum in zip(axarr, zs, UI, ranges):
        scat = ax.scatter(x, y, c=z, s=100, cmap='rainbow')
        label = 'Uniformity: %i'%unif
        if not efficiency:
            label += '    %i ppm'%rangenum
        ax.set_xlabel(label)

    # Colorbar [left, bottom, width, height
    cax = fig.add_axes([0.2, 0.1, 0.6, 0.05])
    cbar = fig.colorbar(scat, cax, orientation='horizontal')
    cbar.set_label('This is a colorbar')
    plt.show()


def main():
    x, y = np.meshgrid(np.arange(10), np.arange(10))
    zs = [np.random.rand(*y.shape) for _ in range(3)]
    plotter(x.flatten(), y.flatten(), zs, 'name', None)

if __name__ == "__main__":
    main()

在这里输入图片描述

1

要设置横坐标的标签,可以使用 ax.set_xlabel('均匀性: ' + unif)。想了解更多信息,可以在 这里查看坐标轴的文档。

你提到的例子使用了图形的 add_axes 方法,作为 add_subplot 的另一种选择。关于 add_axes 中的数字,图形的文档解释说:“在位置 rect [左, 下, 宽, 高] 添加一个坐标轴,所有数值都是相对于图形宽度和高度的比例。”

rect = l,b,w,h
fig.add_axes(rect)

撰写回答