首页 文章

如何在一个图中为不同的图形获得不同的彩色线条?

提问于
浏览
149

我正在使用 matplotlib 创建绘图 . 我必须用不同颜色识别每个绘图,这些颜色应该由Python自动生成 .

你能给我一个方法,在同一个图中为不同的地块添加不同的颜色吗?

4 回答

  • 2

    Matplotlib默认执行此操作 .

    例如 . :

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(10)
    
    plt.plot(x, x)
    plt.plot(x, 2 * x)
    plt.plot(x, 3 * x)
    plt.plot(x, 4 * x)
    plt.show()
    

    Basic plot demonstrating color cycling

    而且,正如您可能已经知道的那样,您可以轻松添加图例:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(10)
    
    plt.plot(x, x)
    plt.plot(x, 2 * x)
    plt.plot(x, 3 * x)
    plt.plot(x, 4 * x)
    
    plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')
    
    plt.show()
    

    Basic plot with legend

    如果要控制将循环的颜色:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(10)
    
    plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])
    
    plt.plot(x, x)
    plt.plot(x, 2 * x)
    plt.plot(x, 3 * x)
    plt.plot(x, 4 * x)
    
    plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')
    
    plt.show()
    

    Plot showing control over default color cycling

    希望那有所帮助!如果你不熟悉matplotlib,the tutorial is a good place to start .

    Edit:

    首先,如果你想要在一个数字上绘制很多(> 5)的东西,可以:

    • 将它们放在不同的图上(考虑在一个图上使用一些子图),或

    • 使用颜色以外的其他颜色(即标记样式或线条粗细)来区分它们 .

    否则,你将陷入一个非常混乱的阴谋!很高兴谁会读到你想要将15种不同的东西塞进一个人物中的任何东西!

    除此之外,许多人在不同程度上都是色盲,区分众多微妙不同的颜色对于更多的人来说比你可能意识到的要困难 .

    话虽如此,如果你真的想在一个轴上放20条线,并且有20种相对不同的颜色,这是一种方法:

    import matplotlib.pyplot as plt
    import numpy as np
    
    num_plots = 20
    
    # Have a look at the colormaps here and decide which one you'd like:
    # http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
    colormap = plt.cm.gist_ncar
    plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, num_plots)])
    
    # Plot several different functions...
    x = np.arange(10)
    labels = []
    for i in range(1, num_plots + 1):
        plt.plot(x, i * x + 5 * i)
        labels.append(r'$y = %ix + %i$' % (i, 5*i))
    
    # I'm basically just demonstrating several different legend options here...
    plt.legend(labels, ncol=4, loc='upper center', 
               bbox_to_anchor=[0.5, 1.1], 
               columnspacing=1.0, labelspacing=0.0,
               handletextpad=0.0, handlelength=1.5,
               fancybox=True, shadow=True)
    
    plt.show()
    

    Unique colors for 20 lines based on a given colormap

  • 325

    稍后设置它们

    如果您不知道要绘制的图的数量,可以在绘制它们直接从图中使用 .lines 检索数字后更改颜色,我使用此解决方案:

    一些随机数据

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)
    
    
    for i in range(1,15):
        ax1.plot(np.array([1,5])*i,label=i)
    

    您需要的一段代码:

    colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired   
    colors = [colormap(i) for i in np.linspace(0, 1,len(ax1.lines))]
    for i,j in enumerate(ax1.lines):
        j.set_color(colors[i])
    
    
    ax1.legend(loc=2)
    

    结果如下:
    enter image description here

  • 22

    我想对上一篇文章中给出的最后一个循环答案提供一个小的改进(该帖子是正确的,仍然应该被接受) . 标记最后一个示例时所隐含的假设是 plt.label(LIST) 将标签号X放在 LIST 中,并且调用了对应于第X时间 plot 的行 . 我之前遇到过这种方法的问题 . 根据matplotlibs文档(http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item)构建图例和自定义标签的推荐方法是让人感觉标签与您认为的标签一致:

    ...
    # Plot several different functions...
    labels = []
    plotHandles = []
    for i in range(1, num_plots + 1):
        x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
        plotHandles.append(x)
        labels.append(some label)
    plt.legend(plotHandles, labels, 'upper left',ncol=1)
    

    **:Matplotlib Legends not working

  • 0

    TL;DR 不,它不能自动完成 . 对的,这是可能的 .

    图( figure )中的每个绘图( axes )都有自己的颜色循环 - 如果不为每个绘图强制使用不同的颜色,则所有绘图都共享相同的颜色顺序 .

    只有当我们伸展一点"automatically"的意思时,才能自动实现每个绘图中的不同颜色 .


    OP写道

    [...]我必须用不同的颜色识别每个图,这些图应该由[Matplotlib]自动生成 .

    但是...... Matplotlib会自动为每条不同的曲线生成不同的颜色

    In [10]: import numpy as np 
        ...: import matplotlib.pyplot as plt                                                  
    
    In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));                                             
    Out[11]:
    

    enter image description here

    那么为什么OP请求呢?如果我们继续阅读,我们有

    你能给我一个方法,在同一个图中为不同的地块添加不同的颜色吗?

    并且它是有道理的,因为每个绘图(在Matplotlib的用语中每个 axes )都有自己的 color_cycle (或者更确切地说,在2018年,它的 prop_cycle ),并且每个绘图( axes )以相同的顺序重复使用相同的颜色 .

    In [12]: fig, axes = plt.subplots(2,3)                                                    
    
    In [13]: for ax in axes.flatten(): 
        ...:     ax.plot((0,1), (0,1))
    

    enter image description here

    如果这是原始问题的含义,一种可能性是为每个图明确命名不同的颜色 .

    如果在循环中生成绘图(通常发生),我们必须有一个额外的循环变量来覆盖Matplotlib自动选择的颜色 .

    In [14]: fig, axes = plt.subplots(2,3)                                                    
    
    In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'): 
        ...:     ax.plot((0,1), (0,1), short_color_name)
    

    enter image description here

相关问题