【问题标题】:How to avoid line color repetition in matplotlib.pyplot?如何避免 matplotlib.pyplot 中的线条颜色重复?
【发布时间】:2011-08-27 00:40:27
【问题描述】:

我正在使用 matplotlib.pyplot 比较一些算法结果,但是很难理解发生了什么,因为几行具有相同的确切颜色。有没有办法避免这种情况?我不认为 pyplot 只有七种颜色,是吗?

【问题讨论】:

标签: python colors matplotlib plot


【解决方案1】:

对于 Python 3,您可以从上述解决方案中使用:

colormap = plt.cm.nipy_spectral
colors = [colormap(i) for i in np.linspace(0, 1,number_of_plots)]
ax.set_prop_cycle('color', colors)

或:

import seaborn as sns

    colors = sns.color_palette("hls", number_of_plots)
    ax.set_prop_cycle('color', colors)

【讨论】:

    【解决方案2】:

    我还建议使用Seaborn。使用这个库,可以很容易地生成具有所需颜色数量的顺序或定性调色板。还有一个可视化调色板的工具。例如:

    import seaborn as sns
    
    colors = sns.color_palette("hls", 4)
    sns.palplot(colors)
    plt.savefig("pal1.png")
    colors = sns.color_palette("hls", 8)
    sns.palplot(colors)
    plt.savefig("pal2.png")
    colors = sns.color_palette("Set2", 8)
    sns.palplot(colors)
    plt.savefig("pal3.png")
    

    这些是生成的调色板:

    【讨论】:

      【解决方案3】:

      如果您知道要绘制多少个图,最好的办法是在之前定义颜色图:

      import matplotlib.pyplot as plt
      import numpy as np
      
      fig1 = plt.figure()
      ax1 = fig1.add_subplot(111)
      number_of_plots=10
      colormap = plt.cm.nipy_spectral #I suggest to use nipy_spectral, Set1,Paired
      ax1.set_color_cycle([colormap(i) for i in np.linspace(0, 1,number_of_plots)])
      for i in range(1,number_of_plots+1):
          ax1.plot(np.array([1,5])*i,label=i)
      
      ax1.legend(loc=2)  
      

      使用nipy_spectral

      使用Set1

      【讨论】:

      • 我们是否应该担心set_color_cycle()version 1.5 中已被弃用? plt 建议改用set_prop_cycle()(但我还没试过)。
      【解决方案4】:

      Matplotlib 有超过七种颜色。您可以通过多种方式指定颜色(请参阅http://matplotlib.sourceforge.net/api/colors_api.html)。

      例如,您可以使用 html 十六进制字符串指定颜色:

      pyplot.plot(x, y, color='#112233')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 2014-06-17
        • 2017-06-23
        • 1970-01-01
        • 1970-01-01
        • 2020-08-12
        相关资源
        最近更新 更多