matplotlib.patches:具有多种颜色的一个补丁

zac*_*ha2 2 python matplotlib

我可以这样创建一个带有每个类别颜色的自定义图例:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

#one color per patch
#define class and colors
colors = ['#01FF4F', '#FFEB00', '#FF01D7', '#5600CC']
categories = ['A','B','C','D']
#create dict
legend_dict=dict(zip(categories,colors))
#create patches
patchList = []
for key in legend_dict:
        data_key = mpatches.Patch(color=legend_dict[key], label=key)
        patchList.append(data_key)

#plotting
plt.gca()
plt.legend(handles=patchList,ncol=len(categories), fontsize='small')
plt.show()
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个图例,其中每个补丁都由 n 种颜色组成。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

 #multiple colors per patch
 colors = [['#01FF4F','#01FF6F'], ['#FFEB00','#FFEB00'], ['#FF01D7','#FF01D7','#FF01D7'], ['#5600CC']]
 categories = ['A','B','C','D']
 #create dict
 legend_dict=dict(zip(categories,colors))
 print(legend_dict)
Run Code Online (Sandbox Code Playgroud)

A 类补丁的颜色应为“#01FF4F”和“#01FF6F”。对于 B 类,它是“#FFEB00”和“#FFEB00”等等。

Imp*_*est 5

补丁有一个面颜色和一个边缘颜色。所以你可以给它们涂上不同的颜色,比如

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

#one color per patch
#define class and colors
 #multiple colors per patch
colors = [['#01FF4F','#00FFff'], 
           ['#FFEB00','#FFFF00'], 
            ['#FF01D7','#FF00aa'], 
             ['#5600CC','#FF00EE']]
categories = ['A','B','C','D']
#create dict
legend_dict=dict(zip(categories,colors))
#create patches
patchList = []
for key in legend_dict:
        data_key = mpatches.Patch(facecolor=legend_dict[key][0], 
                                  edgecolor=legend_dict[key][1], label=key)
        patchList.append(data_key)

#plotting
plt.gca()
plt.legend(handles=patchList,ncol=len(categories), fontsize='small')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

或者,如果您确实想要不同颜色的不同补丁,您可以创建这些补丁的元组并将它们提供给图例。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerTuple

#one color per patch
#define class and colors
 #multiple colors per patch
colors = [['#01FF4F','#00FFff'], 
           ['#FFEB00','#FFFF00'], 
            ['#FF01D7','#FF00aa'], 
             ['#5600CC','#FF00EE']]
categories = ['A','B','C','D']
#create dict
legend_dict=dict(zip(categories,colors))
#create patches
patchList = []
for cat, col in legend_dict.items():
    patchList.append([mpatches.Patch(facecolor=c, label=cat) for c in col])


plt.gca()
plt.legend(handles=patchList, labels=categories, ncol=len(categories), fontsize='small',
           handler_map = {list: HandlerTuple(None)})

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述