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

120

我想要改变pyplot图例中线条样本的粗细/宽度。

图例中线条样本的线宽与它们在图表中代表的线条相同(所以如果线条y1具有linewidth=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()

示例代码绘图

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

相关问题的回答是通过使用leg.get_frame().set_linewidth(7.0)更改图例边框的linewidth。这不会改变图例内部线条的linewidth

1个回答

57

@ImportanceOfBeingErnest的回答很好,如果你只想改变图例框内的线宽度。但我认为这个过程稍微有点复杂,因为你必须在更改图例线宽度之前先复制handles。此外,它不能改变图例标签字体大小。以下两种方法可以更简洁地同时改变线宽和图例标签字体大小。

方法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()

方法二

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()

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

输出图像


1
如何设置 plt.rcParams.update({'legend.linewidth': 10}),因为它不在键中? - droid192
Matplotlib rc有一个名为legend.fontsize的设置。有关更多信息,请参阅rc文件。 - jdhao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接