问题描述
我可以通过这种方式为每个类别创建一个带有颜色的自定义图例:
I can create a custom legend with a color per category this way:
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种颜色组成.
Now I want to create a legend, where each patch is made up of n colors.
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"等等.
The patch for category A should have the colors '#01FF4F'and '#01FF6F'. For category B it's '#FFEB00' and '#FFEB00' and so on.
推荐答案
补丁有 facecolor 和 edgecolor.所以你可以用不同的方式给它们上色,比如
Patches have a facecolor and an edgecolor. So you can colorize those differently, like
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()
或者,如果您真的想要不同颜色的不同补丁,您可以创建这些补丁的元组并将它们提供给图例.
Or if you really want different patches of different color you can create tuples of those patches and supply them to the legend.
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()
这篇关于matplotlib.patches:一个具有多种颜色的补丁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!