关于python:是否可以忽略Matplotlib的第一个默认颜色进行绘图?

Is it possible to ignore Matplotlib first default color for plotting?

Matplotlib绘制了我的矩阵a的每一列,其中4列由蓝色、黄色、绿色、红色组成。enter image description here

然后,我只绘制矩阵a[:,1:4]中的第二、第三、第四列。是否可以使matplotlib从默认值忽略蓝色,从黄色开始(这样,我的每一行的颜色都与前一行相同)?enter image description here

1
2
3
4
5
6
7
8
9
10
11
12
a = np.cumsum(np.cumsum(np.random.randn(7,4), axis=0), axis=1)

lab = np.array(["A","B","C","E"])

fig, ax = plt.subplots()
ax.plot(a)
ax.legend(labels=lab )
# plt.show()
fig, ax = plt.subplots()
ax.plot(a[:,1:4])
ax.legend(labels=lab[1:4])
plt.show()


用于连续线条的颜色是来自颜色循环器的颜色。要跳过此颜色循环中的颜色,可以调用

1
2
ax._get_lines.prop_cycler.next()  # python 2
next(ax._get_lines.prop_cycler)   # python 2 or 3

完整的示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np
import matplotlib.pyplot as plt

a = np.cumsum(np.cumsum(np.random.randn(7,4), axis=0), axis=1)
lab = np.array(["A","B","C","E"])

fig, ax = plt.subplots()
ax.plot(a)
ax.legend(labels=lab )

fig, ax = plt.subplots()
# skip first color
next(ax._get_lines.prop_cycler)
ax.plot(a[:,1:4])
ax.legend(labels=lab[1:4])
plt.show()

为了跳过第一种颜色,我建议使用

1
plt.rcParams['axes.prop_cycle'].by_key()['color']

如本问题/答案所示。然后使用以下方法设置当前轴的颜色循环:

1
plt.gca().set_color_cycle()

因此,您的完整示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
a = np.cumsum(np.cumsum(np.random.randn(7,4), axis=0), axis=1)

lab = np.array(["A","B","C","E"])
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

fig, ax = plt.subplots()
ax.plot(a)
ax.legend(labels=lab )

fig1, ax1 = plt.subplots()
plt.gca().set_color_cycle(colors[1:4])
ax1.plot(a[:,1:4])
ax1.legend(labels=lab[1:4])
plt.show()

它给出:

enter image description here

enter image description here


您可以在调用ax.plot(a[:,1:4])之前,向ax.plot([],[])插入一个额外的调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
a = np.cumsum(np.cumsum(np.random.randn(7,4), axis=0), axis=1)

lab = np.array(["A","B","C","E"])

fig, ax = plt.subplots()
ax.plot(a)
ax.legend(labels=lab )
# plt.show()
fig, ax = plt.subplots()
ax.plot([],[])
ax.plot(a[:,1:4])
ax.legend(labels=lab[1:4])
plt.show()

我有这样的印象,你要确保每一个colone都保持一个明确的颜色。为此,可以创建与要显示的每个列匹配的颜色向量。可以创建颜色向量。颜色=["蓝色"、"黄色"、"绿色"、"红色"]

1
2
3
4
5
6
7
8
9
10
11
12
13
a = np.cumsum(np.cumsum(np.random.randn(7,4), axis=0), axis=1)

lab = np.array(["A","B","C","E"])
color = ["blue","yellow","green","red"]

fig, ax = plt.subplots()
ax.plot(a, color = color)
ax.legend(labels=lab )
# plt.show()
fig, ax = plt.subplots()
ax.plot(a[:,1:4])
ax.legend(labels=lab[1:4], color = color[1:4])
plt.show()