【问题标题】:Changing colour scheme of python matplotlib python plots [duplicate]更改python matplotlib python图的配色方案[重复]
【发布时间】:2013-11-30 00:44:07
【问题描述】:

我想为我的 python 图设置一个配色方案,这样它们就不会像下面显示的顶部图中的 A 和 H 那样重复相同的颜色。 (抱歉,如果很难看到)。

我使用的代码很简单,

ax1.plot(sections,A,label='A',linewidth=2) ax1.plot(sections,B,label='B',linewidth=2) ax1.plot(sections,C,label='C',linewidth=2) ax1.plot(sections,D,label='D',linewidth=2) ax1.plot(sections,E,label='E',linewidth=2) ax1.plot(sections,F,label='F',linewidth=2) ax1.plot(sections,G,label='G',linewidth=2) ax1.plot(sections,H,label='H',linewidth=2)

设置配色方案的最佳方法是什么?是否使用颜色图功能?感谢您的帮助!

【问题讨论】:

    标签: python colors matplotlib plot color-mapping


    【解决方案1】:

    您可以使用一些颜色图为线条着色,例如(这里我使用“jet”颜色图):

    >>> from matplotlib import cm
    >>> for i, val in enumerate(cm.jet(linspace(0,1,10))): #different lines
        plt.plot(arange(10), arange(10)+i, color=val, linestyle='-')
    

    要在您现有的代码中以最少的更改执行此操作,只需添加(并且不要忘记将 10 更改为您拥有的绘图数。):

    for L, C in zip([item for item in ax.get_children() if isinstance(item, matplotlib.lines.Line2D)], cm.jet(linspace(0,1,10))):
        L.set_color(C)   
    

    【讨论】:

    • 感谢您的帮助,但我很难理解如何在我编写的脚本中使用它。有没有办法我可以按照 ax1.cm.ScalarMappable(cmap='jet')
    • 我在您的代码中收到一条错误消息,提示“NameError: name 'matplotlib' is not defined”。我之前使用 import "matplotlib.pyplot as plt" 和 "from matplotlib import *" 定义了 matplotlib,这有什么问题吗?
    • 是的,添加import matplotlib,当然,:-)。但既然你已经有from matplotlib import *,你只需要lines.Line2D 而不是matplotlib.lines.Line2D
    • 感谢您的帮助,现在可以使用了!干杯!
    • 什么代表 cm.jet(x) 返回的值(其中 x 是任意数字)?
    【解决方案2】:

    您可以使用set_color_cycle() 方法更改特定轴的颜色图。

    这是matplotlib 文档中color cycle demo 的简化版本:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 2 * np.pi)
    offsets = np.linspace(0, 2*np.pi, 4, endpoint=False)
    yy = np.transpose([np.sin(x + phi) for phi in offsets])
    
    plt.rc('lines', linewidth=4)
    
    ax = plt.gca()
    
    # Set color cycle for this axes 
    ax.set_color_cycle(['c', 'm', 'y', 'k'])
    
    ax.plot(yy)
    
    plt.show()
    

    另一个选项是更改全局默认颜色映射。您可以通过creating a matplotlibrc file 并在此处设置axes.color_cyle 来执行此操作,或者在运行时更改运行配置:

    import matplotlib
    matplotlib.rcParams['axes.color_cycle'] = ['r', 'g', 'b']
    

    您还可以使用 HTML 十六进制表示法来指定颜色:

    ax.set_color_cycle(['#FF0000', '#00FF00', '#0000FF'])
    

    有关如何指定颜色的详细信息,请参阅documentation of the `color``module

    matplotlib.cm module 也很有用,例如用于注册您自己的颜色图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2017-12-05
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多