Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Matplotlib:如何将填充颜色贴图的小矩形绘制为图例_Python_Matplotlib_Legend_Colormap - Fatal编程技术网

Python Matplotlib:如何将填充颜色贴图的小矩形绘制为图例

Python Matplotlib:如何将填充颜色贴图的小矩形绘制为图例,python,matplotlib,legend,colormap,Python,Matplotlib,Legend,Colormap,我不想在绘图旁边绘制一个颜色条,而是想绘制一个充满颜色贴图的小矩形作为图例 通过执行以下技巧,我已经可以绘制一个填充任何颜色的小矩形: axis0, = myax.plot([], linewidth=10, color='r') axis =[axis0] legend=['mytext'] plt.legend(axis, legend) 我可以用彩色地图做同样的事情吗?谢谢 据我所知,除了从头开始创建矩形和图例之外,没有其他方法可以做到这一点。以下是一种方法(主

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

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

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

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

plt.legend(axis,
           legend)

我可以用彩色地图做同样的事情吗?谢谢

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

如果计划对多个打印执行此操作,则可能需要创建一个,如中所示。您还可以考虑显示COLLBAR的其他方法,例如在所示的示例中和./P> 文档:

在我的软件包中,我实现了一个名为
set\u cmap\u legend\u entry()
的函数。 您可以给它一个plot元素和标签,它会自动为它创建一个colormap图例条目,如下图所示(有关此项的文档,请参阅):


谢谢@Patrick FitzGerald,我来试试!
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()