matplotlib 我如何给给予不同的标签?[重复]

sbtkgmzw  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(133)

此问题已在此处有答案

Change main plot legend label text(4个答案)
How to make two markers share the same label in the legend(5个答案)
Combine multiple line labels in legend(9个回答)
Sharing the same label for two plots with line and point markers in legend(2个答案)
上个月关门了。
我在比较微分方程的解析解和数值解这两种解法。我想用“解析解”来标记实线,用“数值解”来标记虚线,然后给予每种颜色一个不同的标记。
我该怎么做呢?

下面是我用来生成图表的代码

fig1 = plt.scatter(t, I, s=15, label='Numerical')
fig2 = plt.plot(t, it, label='Analytical')
fig3 = plt.scatter(t, S, s=15, label='Numerical')
fig4 = plt.plot(t, st, label='Analytical')
euoag5mw

euoag5mw1#

这里有一种方法,基于matplotlib文档中的"Composing Custom Legends"

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

# -- DATA
t = np.linspace(-5, 5, 40)

# Analytical
a1 = np.tanh(t)
a2 = -np.tanh(t) + 1

# Numerical
n1 = a1 + np.random.randn(*a1.shape) / 50
n2 = a2 + np.random.randn(*a2.shape) / 50

# -- PLOTS
fig, ax = plt.subplots()

# Colors
clr1 = "C0"
clr2 = "C1"

# Analytical solution
ax.plot(t, a1, color=clr1)
ax.plot(t, a2, color=clr2)

# Numerical solution
ax.scatter(t, n1, color=clr1)
ax.scatter(t, n2, color=clr2)

# Custom legend
# https://matplotlib.org/stable/gallery/text_labels_and_annotations/custom_legends.html

legend_elements = [
    Patch(color=clr1, label="Exp. 1"),
    Patch(color=clr2, label="Exp. 2"),
    Line2D(
        [0],
        [0],
        marker="o",
        color="k",
        lw=0,
        label="Numerical",
    ),
    Line2D(
        [0],
        [0],
        color="k",
        label="Analytical",
    ),
]
ax.legend(handles=legend_elements, ncols=2)

plt.show()

相关问题