更改matplotlib pyplot图例中线条的线宽

Aln*_*tak 42 python matplotlib

我想更改pyplot图例中的线样本的厚度/宽度.

图例中线样的线宽与它们在图中表示的线相同(因此,如果线y1linewidth=7.0,则图例的相应y1标签也将具有linewidth=7.0).

我希望图例线比图中的线条更粗.

例如,以下代码生成以下图像:

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1',linewidth=7.0)
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

示例代码图

我想y1在图例中设置标签linewidth=7.0,而图中的y1线条具有不同的宽度(linewidth=1.0).

我没有成功在线寻找解决方案.唯一相关的问题是有关更改图例边界框的线宽的答案leg.get_frame().set_linewidth(7.0).这不会改变线的线宽的传奇.

jdh*_*hao 24

@ImportanceOfBeingErnest的答案很好,如果您只想更改图例框内的线宽.但我认为它有点复杂,因为你必须在更改图例线宽之前复制句柄.此外,它无法更改图例标签fontsize.以下两种方法不仅可以更简洁地更改线宽,还可以更改图例标签文本字体大小.

方法1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()
Run Code Online (Sandbox Code Playgroud)

方法2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
Run Code Online (Sandbox Code Playgroud)

以上两种方法产生相同的输出图像:

输出图像