gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:45:55 45 4
gpt4 key购买 nike

我想更改 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()

example code plot

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

相关问题有通过leg.get_frame().set_linewidth(7.0)改变图例边界框linewidth的答案。这不会改变图例行的linewidth

最佳答案

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

方法一

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

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

output image

关于python - 更改 matplotlib pyplot 图例中线条的线宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42758897/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com