简体   繁体   English

Matplotlib:如何绘制一个填充有颜色图的小矩形作为图例

[英]Matplotlib: How to plot a small rectangle filled with a colormap as a legend

Instead of a plotting a colorbar next to my plot, I want to plot a small rectangle filled with the colormap as a legend.而不是在我的情节旁边绘制一个颜色条,我想绘制一个填充颜色图的小矩形作为图例。

I already can plot a small rectangle filled with any color, by doing the following trick:通过执行以下技巧,我已经可以绘制一个填充任何颜色的小矩形:

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

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

plt.legend(axis,
           legend)

Can I do the same with a colormap?我可以对颜色图做同样的事情吗? Thanks!谢谢!

To my knowledge, there is no way of doing this other than by creating the rectangle and legend from scratch.据我所知,除了从头开始创建矩形和图例之外,没有其他方法可以做到这一点。 Here is one approach (based mainly on 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()

Legend_colormap

If you plan on doing this for multiple plots, you may want to create a custom legend handler as shown in this answer .如果您计划对多个图执行此操作,您可能需要创建一个自定义图例处理程序,如本答案所示。 You may also want to consider other ways of displaying the colorbar, such as in the examples shown here and here and here .您可能还需要考虑显示颜色栏的其他方式,例如在此处此处以及此处显示的示例中。

Documentation:legend guide文档:图例指南

In my CMasher package, I implemented a function called set_cmap_legend_entry() that does exactly this for you.在我的CMasher包中,我实现了一个名为set_cmap_legend_entry()的函数,它完全可以为您执行此操作。 You can give it a plot element and a label, and it will automatically create a colormap legend entry for it, like for the image shown below (see here for the documentation on this):你可以给它一个绘图元素和一个标签,它会自动为它创建一个颜色图图例条目,就像下面显示的图像一样(参见 这里的文档):

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM