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

问题描述 投票:1回答:2

我正在使用以下代码通过使用matplotlib在Python中生成带有大量过度绘制的线的图:

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

这将产生如下图:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9tcU5QZC5wbmcifQ==” alt =“在此处输入图像描述”>

问题是图例-因为绘制的线条具有很高的透明度,所以图例线条也是如此,这很难阅读。另外,它绘制了我怀疑是“前两行”的线,并且当我需要一个红色和一个蓝色时,它们都是红色的。

[我看不到任何在Matplotlib中调整线条颜色的方法,就像我说的R图形库一样,但是没有人有可靠的解决方法吗?

python matplotlib data-visualization
2个回答
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()

我还没有测试代码本身,但是我经常做类似的事情来绘制大套线,并在每个图套上画一条图例。>


0
投票

当我运行您的代码时出现错误,但这应该可以解决问题:

© www.soinside.com 2019 - 2024. All rights reserved.