使用matplotlib调整图例中的线条颜色

1 投票
2 回答
7735 浏览
提问于 2025-04-17 13:40

我正在使用以下代码,在Python中利用matplotlib生成一个包含很多重叠线条的图:

def a_run(n, t, s):
    xaxis = np.arange(t, dtype=float)
    #Scale x-axis by the step size
    for i in xaxis:
        xaxis[i]=(xaxis[i]*s)
    for j in range(n):
        result = a_solve(t,s)
        plt.plot(result[:,1], color = 'r', alpha=0.1)

def b_run(n, t, s):
    xaxis = np.arange(t, dtype=float)
    #Scale x-axis by the step size
    for i in xaxis:
        xaxis[i]=(xaxis[i]*s)
    for j in range(n):
        result = b_solve(t,s)
        plt.plot(result[:,1], color = 'b', alpha=0.1)

a_run(100, 300, 0.02)
b_run(100, 300, 0.02)   

plt.xlabel("Time")
plt.ylabel("P")
plt.legend(("A","B"), shadow=True, fancybox=True) Legend providing same color for both
plt.show()

这样生成的图像看起来是这样的:

在这里输入图片描述

问题出在图例上——因为线条的透明度很高,所以图例中的线条也变得很透明,这样就很难看清楚。此外,它似乎只绘制了“前两条”线,而且都是红色的,而我需要一条红色和一条蓝色的。

我在Matplotlib中找不到像在R图形库中那样调整线条颜色的方法,不知道有没有什么好的解决办法?

2 个回答

3

当我运行你的代码时出现了一个错误,但这个方法应该可以解决问题:

from matplotlib.lines import Line2D

custom_lines = [Line2D([0], [0], color='red', lw=2),
            Line2D([0], [0], color='blue', lw=2)]

plt.legend(custom_lines, ['A', 'B'])

参考链接:自定义图例的制作

5

如果你要画很多条线,使用LineCollection会让你的程序跑得更快。

import matplotlib.collections as mplcol
import matplotlib.colors as mplc

def a_run(n, t, s):
    xaxis = np.arange(t, dtype=float)
    #Scale x-axis by the step size
    for i in xaxis:
        xaxis[i]=(xaxis[i]*s)
    result = [a_solve(t,s)[:,1] for j in range(n)]
    lc = mplcol.LineCollection(result, colors=[mplc.to_rgba('r', alpha=0.1),]*n)
    plt.gca().add_collection(lc)
    return ls

[...]
lsa = a_run(...)
lsb = b_run(...)    
leg = plt.legend((lsa, lsb),("A","B"), shadow=True, fancybox=True)
#set alpha=1 in the legend
for l in leg.get_lines():
    l.set_alpha(1)
plt.draw()

我没有测试过这段代码,但我经常会做类似的事情,画很多条线,并且每一组线都有一个对应的图例。

撰写回答