【问题标题】:Adjusting the Line Colors in a Legend using matplotlib使用 matplotlib 调整图例中的线条颜色
【发布时间】:2013-01-25 16:28:46
【问题描述】:

我正在使用以下代码在 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 图形库中所说的那样,但是有人有可靠的解决方法吗?

【问题讨论】:

    标签: python matplotlib data-visualization


    【解决方案1】:

    如果你绘制了很多线,你应该使用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()
    

    我没有测试过代码本身,但我经常做一些类似的事情来绘制大量的线,并有一个图例,每组绘制一条线

    【讨论】:

      【解决方案2】:

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

      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'])
      

      参考:Composing Custom Legends

      【讨论】:

        猜你喜欢
        • 2022-07-05
        • 2018-02-28
        • 2017-09-02
        • 2021-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-08
        相关资源
        最近更新 更多