【问题标题】:How to cycle through colors in a plot for each iteration of a for loop如何在 for 循环的每次迭代中循环显示绘图中的颜色
【发布时间】:2020-07-20 02:22:45
【问题描述】:

我正在尝试运行一个 for 循环,该循环在 for 循环的每次迭代中循环使用颜色。我发现类似的问题通过颜色循环,但不是依赖于特定 for 循环的问题。我在下面提供了一些链接:

How to pick a new color for each plotted line within a figure in matplotlib?

matplotlib.cycler

Color cycler demo

我的代码用于简单的随机游走

# Parameters
ntraj=10
n=20
p=0.4

# Initialize holder for trajectories
xtraj=np.zeros(n+1,float)

# Simulation
for j in range(ntraj):
    for i in range(n):
        xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0

    plt.plot(range(n+1),xtraj,'b-',alpha=0.2)
plt.title("Simple Random Walk")  

我想为每个j 创建一条不同颜色的线。如果答案很明显,我很抱歉。我是python新手。

【问题讨论】:

    标签: python for-loop matplotlib colors


    【解决方案1】:

    就像现在一样,每行都会采用新的颜色。如果您想限制选择并遍历列表,您可以使用itertools.cycle

    from itertools import cycle
    
    colours = cycle(['red', 'green', 'blue'])
    
    
    # Simulation
    for j in range(ntraj):
        for i in range(n):
            xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
    
        plt.plot(range(n+1),xtraj,'b-',alpha=0.2, color=colours.next())
    
    

    【讨论】:

    • 感谢@Alexey_Mints 如果尝试循环使用颜色,这很有效。
    【解决方案2】:

    我添加了一个颜色列表。我很确定它们可以是 RGB 或 Hex。然后在 j 循环内,颜色将切换到下一个索引。

    colors = ['b','g','r','c','m','y']
    # Parameters
    
    # Simulation
    for j in range(ntraj):
        color = colors[j % len(colors)]
        for i in range(n):
            xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
    
        plt.plot(range(n+1),xtraj,"{}-".format(color),alpha=0.2)
    plt.title("Simple Random Walk")  
    

    【讨论】:

      【解决方案3】:

      matplotlib.cm中选择您喜欢的任何调色板

      试试:

      # Parameters
      ntraj=10
      n=20
      p=0.4
      
      colors = plt.cm.jet(np.linspace(0,1,ntraj))# Initialize holder for trajectories
      xtraj=np.zeros(n+1,float)
      
      
      # Simulation
      for j in range(ntraj):
          for i in range(n):
              xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
      
          plt.plot(range(n+1),xtraj,'b-',alpha=0.2, color=colors[j])
      
      plt.title("Simple Random Walk")
      

      【讨论】:

      • 您可以在 plt.plot 中按线宽增加线的粗细...更好地使用linewidth=2.0
      【解决方案4】:

      您有几个使用 matplotlib.pylplot 的选项。

      除了已经提供的解决方案之外,您还可以直接定义颜色并根据您的 for 循环更改值:

       # Parameters
      ntraj=10
      n=20
      p=0.4
      
      xtraj=np.zeros(n+1,float)
      
      
      # Simulation
      for j in range(ntraj):
          for i in range(n):
              xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
      
          ctemp = 0.1+(j-1)/ntraj
          plt.plot(range(n+1),xtraj,'b-',alpha=0.2, color=(ctemp, ctemp, ctemp))
      
      plt.title("Simple Random Walk")
      

      【讨论】:

        猜你喜欢
        • 2019-08-16
        • 2015-02-10
        • 2021-03-28
        • 2017-04-28
        • 2018-02-13
        • 2018-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多