如何在matplotlib中为线图迭代的子集设置不同的颜色?

时间:2019-07-25 07:19:26

标签: python matplotlib plot colors iteration

我正在反复绘制来自2D数组np.exp(12,5000)的12行数据的out_array结果。所有数据共享相同的x值(x_d)。我希望所有图形的前4个迭代都使用相同的颜色,接下来的4个使用不同的颜色,接下来的4个使用不同的颜色...这样我可以使用3种不同的颜色,每种颜色分别对应于1th-4th,5th-8th ,以及第9-12次迭代。最后,最好在图例中定义这些集合及其相应的颜色。

我研究了cyclerhttps://matplotlib.org/examples/color/color_cycle_demo.html),但无法弄清楚如何将颜色分配给迭代次数> 1(在我的情况下为4)。如您在我的代码示例中所见,我可以用不同的(默认)颜色绘制所有12条线-或者-我知道如何使它们全部具有相同的颜色(即...,color = 'r',...

plt.figure()
for i in range(out_array.shape[0]):
    plt.plot(x_d, np.exp(out_array[i]),linewidth = 1, alpha = 0.6)
plt.xlim(-2,3)

我期望这样的图,总共只有3种不同的颜色,每种颜色对应于上述迭代的块。 12 lines all with different colors

2 个答案:

答案 0 :(得分:1)

plt.figure()
n = 0
color = ['r','g','b']
for i in range(out_array.shape[0]):
    n = n+1
    if n/4 <= 1:
        c = 1
    elif n/4 >1 and n/4 <= 2:
        c = 2
    elif n/4 >2:
        c = 3
    else:
        print(n)
    plt.plot(x_d, np.exp(out_array[i]),color = color[c-1])
plt.show()

enter image description here

答案 1 :(得分:1)

其他解决方案

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

color = ['r', 'g', 'b', 'p']

for i in range(12):

    plt.plot(x, i*x, color[i//4])

plt.show()