【问题标题】:Change line width of lines in matplotlib pyplot legend [duplicate]更改matplotlib pyplot图例中线条的线宽[重复]
【发布时间】:2017-03-13 08:05:47
【问题描述】:

我想更改 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) 更改图例边界框线宽的答案。这不会改变图例内行的线宽。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

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

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

    【讨论】:

    • 如何使用plt.rcParams.update({'legend.linewidth': 10}) 设置它,因为它不在键中?
    • matplotlib rc 有一个设置legend.fontsize。有关详细信息,请参阅 rc 文件。
    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 2020-10-09
    • 2012-03-31
    • 1970-01-01
    • 2015-03-27
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多