python-3.x Matplotlib:默认情况下将线的图例索引显示为面片

o7jaxewo  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(122)

有关背景信息,请参见legend guide
我想将Line2D对象的图例标示预设显示为Patches(具有相同的色彩和标签)。最简洁的方式是什麽?我尝试将update_default_handler_maphandler_map搭配使用,但总是发生错误。

carvr3hs

carvr3hs1#

您可以执行以下操作将图例显示为修补:

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

colors = [['#01FF4F','#00FFff'],
           ['#FFEB00','#FFFF00']]
categories = ['A','B']
# categories and colors inside a dict
legend_dict=dict(zip(categories,colors))
# setting up lines for the plot and list for patches
patchList = []
fig, ax = plt.subplots()
# assigning each inner color for each categories to their respective plot lines and legend/patches
for key in legend_dict:
        data_key = mpatches.Patch(facecolor=legend_dict[key][0],
                                  edgecolor=legend_dict[key][1], label=key)
        ax.plot(np.random.randn(100).cumsum(), color=legend_dict[key][0], label=legend_dict[key][1])
        patchList.append(data_key)

ax.legend(handles=patchList, ncol=len(categories), fontsize='small')
plt.show()

输出:

在给出这个答案之前,我并不了解matplotlib,所以我不得不混合了两三个SO post才走到这一步(尝试/失败了一段时间)。

既然您提到了Line 2d:

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.lines import Line2D

colors = [['#01FF4F','#00FFff'],
           ['#FFEB00','#FFFF00']]
categories = ['A','B']
# categories and colors inside a dict
legend_dict=dict(zip(categories,colors))
# setting up lines for the plot and list for patches
patchList = []
fig, ax = plt.subplots()
# assigning each inner color for each categories to their respective plot lines and legend/patches
for key in legend_dict:
        data_key = mpatches.Patch(facecolor=legend_dict[key][0],
                                  edgecolor=legend_dict[key][1], label=key)
        ax.plot(Line2D(np.random.randn(100).cumsum(), np.random.randn(100).cumsum()).get_data(), color=legend_dict[key][0], label=legend_dict[key][1])
        patchList.append(data_key)

ax.legend(handles=patchList, ncol=len(categories), fontsize='small')
plt.show()

输出:

一个耐人寻味的和补丁相关的帖子让我忍不住链接了起来:Make patches bigger used as legend inside matplotlib
最后,这里是一个关于在matplotlib上定制图例的不错的摘录:https://jakevdp.github.io/PythonDataScienceHandbook/04.06-customizing-legends.html

vmdwslir

vmdwslir2#

默认情况下显示此选项可能不起作用,因为线条和补丁之间存在太多差异。线条可以有线宽、标记、线条样式等。补丁可以有轮廓、阴影线等。
对于只有彩色的简单情况,可以使用矩形:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.random.randn(100).cumsum(), color='tomato', label='red line')
ax.plot(np.random.randn(100).cumsum(), color='cornflowerblue', alpha=0.6, label='blue line')

handles, labels = ax.get_legend_handles_labels()
new_handles = [h if type(h) != matplotlib.lines.Line2D
               else plt.Rectangle((0, 0), 0, 0, lw=0, color=h.get_color(), alpha=h.get_alpha()) for h in handles]

ax.legend(new_handles, labels)
plt.show()

相关问题