【问题标题】:Matplotlib: How to plot a small rectangle filled with a colormap as a legendMatplotlib:如何绘制一个填充有颜色图的小矩形作为图例
【发布时间】:2016-11-24 02:36:33
【问题描述】:

我不想在我的绘图旁边绘制一个颜色条,而是绘制一个填充有颜色图的小矩形作为图例。

通过以下技巧,我已经可以绘制一个填充任何颜色的小矩形:

axis0, = myax.plot([], linewidth=10, color='r')

axis =[axis0]
legend=['mytext']

plt.legend(axis,
           legend)

我可以对颜色图做同样的事情吗?谢谢!

【问题讨论】:

    标签: python matplotlib legend colormap


    【解决方案1】:

    据我所知,除了从头开始创建矩形和图例之外,没有其他方法可以做到这一点。这是一种方法(主要基于this answer):

    import numpy as np                                    # v 1.19.2
    import matplotlib.pyplot as plt                       # v 3.3.2
    import matplotlib.patches as patches
    from matplotlib.legend_handler import HandlerTuple
    
    rng = np.random.default_rng(seed=1)
    
    ncmaps = 5     # number of colormaps to draw for illustration
    ncolors = 100  # number high enough to draw a smooth gradient for each colormap
    
    # Create random list of colormaps and extract list of colors to 
    # draw the gradient of each colormap
    cmaps_names = list(rng.choice(plt.colormaps(), size=ncmaps))
    cmaps = [plt.cm.get_cmap(name) for name in cmaps_names]
    cmaps_gradients = [cmap(np.linspace(0, 1, ncolors)) for cmap in cmaps]
    cmaps_dict = dict(zip(cmaps_names, cmaps_gradients))
    
    # Create a list of lists of patches representing the gradient of each colormap
    patches_cmaps_gradients = []
    for cmap_name, cmap_colors in cmaps_dict.items():
        cmap_gradient = [patches.Patch(facecolor=c, edgecolor=c, label=cmap_name)
                         for c in cmap_colors]
        patches_cmaps_gradients.append(cmap_gradient)
    
    # Create custom legend (with a large fontsize to better illustrate the result)
    plt.legend(handles=patches_cmaps_gradients, labels=cmaps_names, fontsize=20,
               handler_map={list: HandlerTuple(ndivide=None, pad=0)})
    
    plt.show()
    

    如果您打算为多个地块执行此操作,您可能需要创建一个custom legend handler,如this answer 所示。您可能还需要考虑显示颜色条的其他方式,例如在here 和here 和here 显示的示例中。

    文档:legend guide

    【讨论】:

    • 谢谢@Patrick FitzGerald,我试试看!
    【解决方案2】:

    在我的CMasher 包中,我实现了一个名为set_cmap_legend_entry() 的函数,它完全可以为您完成此任务。 您可以给它一个绘图元素和一个标签,它会自动为其创建一个颜色图图例条目,如下图所示(有关此文档,请参阅here):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多