Python Matplotlib:打印自定义图例

Python Matplotlib:打印自定义图例,python,matplotlib,Python,Matplotlib,在这种情况下,我将内容打印在matplotlib绘图上,散点图形状映射到标签类型 例如: 's': "X" 'o': "Y" 然而,我用网络x绘制。现在,我想添加一个显示此映射的图例,我可以使用plt方法修改绘图 因此,我需要以某种方式plt.legend plt.legend(('s','o'),("X","Y")) 但是,从文档中不清楚如何完成这项任务。有没有办法在matplotlib中绘制这样的自定义图例?在轴上绘制对象时,可以传递标签关键字参数: fig, ax = plt.subp

在这种情况下,我将内容打印在matplotlib绘图上,散点图形状映射到标签类型

例如:

's': "X"
'o': "Y"
然而,我用网络x绘制。现在,我想添加一个显示此映射的图例,我可以使用
plt
方法修改绘图

因此,我需要以某种方式
plt.legend

plt.legend(('s','o'),("X","Y"))

但是,从文档中不清楚如何完成这项任务。有没有办法在matplotlib中绘制这样的自定义图例?

轴上绘制对象时,可以传递
标签
关键字参数:

fig, ax = plt.subplots(figsize=(8, 8))

n_points = 10
x1 = np.random.rand(n_points)
y1 = np.random.rand(n_points)
x2 = np.random.rand(n_points)
y2 = np.random.rand(n_points)

ax.scatter(x1, y1, marker='x', label='X')
ax.scatter(x2, y2, marker='o', label='y')
ax.legend()
这会产生如下结果:


轴上绘制对象时,可以传递
标签
关键字参数:

fig, ax = plt.subplots(figsize=(8, 8))

n_points = 10
x1 = np.random.rand(n_points)
y1 = np.random.rand(n_points)
x2 = np.random.rand(n_points)
y2 = np.random.rand(n_points)

ax.scatter(x1, y1, marker='x', label='X')
ax.scatter(x2, y2, marker='o', label='y')
ax.legend()
这会产生如下结果:


从你的问题中不清楚你所说的映射是什么意思。如果要将图例控制柄从默认标记修改为自定义变量标记,可以执行以下操作。我的解决方案是基于答案的,但经过简化,以呈现一个简单的案例。别忘了对原来的答案投赞成票。我已经承认了

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

fig, ax = plt.subplots()

new_legends = ["X", "Y"]
markers = ['s', 'o']
colors = ['r', 'b']

x = np.arange(5)
plt.plot(x, 1.5*x, marker=markers[0], color=colors[0], label='squares')
plt.plot(x, x, marker=markers[1], color=colors[1], label='circles')

_, labels = ax.get_legend_handles_labels()

def dupe_legend(label, color):
    line = Line2D([0], [0], linestyle='none', mfc='black',
                mec=color, marker=r'$\mathregular{{{}}}$'.format(label))
    return line

duplicates = [dupe_legend(leg, color) for leg, color in zip(new_legends, colors)]
ax.legend(duplicates, labels, numpoints=1, markerscale=2, fontsize=16)
plt.show()

从你的问题中不清楚你所说的映射是什么意思。如果要将图例控制柄从默认标记修改为自定义变量标记,可以执行以下操作。我的解决方案是基于答案的,但经过简化,以呈现一个简单的案例。别忘了对原来的答案投赞成票。我已经承认了

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

fig, ax = plt.subplots()

new_legends = ["X", "Y"]
markers = ['s', 'o']
colors = ['r', 'b']

x = np.arange(5)
plt.plot(x, 1.5*x, marker=markers[0], color=colors[0], label='squares')
plt.plot(x, x, marker=markers[1], color=colors[1], label='circles')

_, labels = ax.get_legend_handles_labels()

def dupe_legend(label, color):
    line = Line2D([0], [0], linestyle='none', mfc='black',
                mec=color, marker=r'$\mathregular{{{}}}$'.format(label))
    return line

duplicates = [dupe_legend(leg, color) for leg, color in zip(new_legends, colors)]
ax.legend(duplicates, labels, numpoints=1, markerscale=2, fontsize=16)
plt.show()