【问题标题】:Add legend of whole numbers instead of gradient in matplotlib在 matplotlib 中添加整数图例而不是渐变
【发布时间】:2020-03-26 17:14:05
【问题描述】:

我想添加一个只有整数的图例,即 0,1,2,3...14,而不是渐变色条。基本上,我希望数组值在图例中具有唯一的颜色和标签,以便您可以清楚地区分数组中的每个值。

fileloc=os.path.join(basepath, infile)
data=np.loadtxt(fileloc)

fig = plt.figure(figsize=(20,10))
plt.imshow(data)
plt.colorbar()

【问题讨论】:

    标签: python arrays numpy matplotlib legend-properties


    【解决方案1】:

    如果我正确理解了这个问题,数据会以整数 numpy 数组的形式给出,这会产生具有恰好 N 种不同颜色的图像。

    要从 viridis 颜色图中获取恰好具有 N 个颜色的颜色图,请使用 plt.cm.get_cmap('viridis', N)。这将产生一个恰好包含 N 个区域的颜色条。

    为了在每个区域的中心很好地获得刻度,将空间分成 2N+1 块,然后取所有奇数位置。 (因此,如果有 5 种颜色,颜色条将从 0 变为 4,这将得到 11 个标记,其中标记 0 被跳过,而使用标记 1、3、5、7 和 9)。可以在每个刻度旁边放置一个带有数字的标签。

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(6, 4))
    
    # create some random test data
    data = np.random.normal(0, 0.05, size=(150, 150)).cumsum(axis=0).cumsum(axis=1)
    data = data.astype(np.int)  # convert to integers
    data -= data.min()  # let the numbers start at zero
    
    num_colors = data.max() + 1
    cmap = plt.cm.get_cmap('viridis', num_colors)
    plt.imshow(data, cmap=cmap)
    cbar = plt.colorbar(ticks=np.linspace(0, num_colors - 1, num_colors * 2 + 1)[1::2])
    cbar.ax.set_yticklabels(range(num_colors))
    
    plt.show()
    

    【讨论】:

    • 这能回答你的问题吗?
    【解决方案2】:

    你可以使用 matplotlib.colors.ListedColormap 如下:

    custom_cmap = colors.ListedColormap(['purple','blue','green','yellow']) #... and so on until you have 15 colours specified
    

    然后将其作为 cmap 参数传递给 imshow 和 colorbar:

    plt.imshow(data, cmap=custom_cmap)
    plt.colorbar(cmap=custom_cmap)
    

    【讨论】:

    • plt.colorbar 没有 cmap 参数。考虑文档。
    猜你喜欢
    • 2017-07-22
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多