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

2024-06-17 12:59:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以通过以下方式创建自定义图例,每个类别有一种颜色:

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()

现在我想创建一个图例,每个补丁由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)

A类的补丁应该有颜色“#01FF4F”和“#01FF6F”。对于B类,是“#FFEB00”和“#FFEB00”,依此类推。你知道吗


Tags: keyimportmatplotlibascreatepltdictcategories
1条回答
网友
1楼 · 发布于 2024-06-17 12:59:05

面片有面色和边色。所以你可以用不同的颜色,比如

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()

enter image description here

或者如果你真的需要不同颜色的补丁,你可以创建这些补丁的元组,并将它们提供给图例。你知道吗

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()

enter image description here

相关问题 更多 >