2017-10-10 49 views
2

Matplotlib繪製了我的矩陣a的每一列,其中4列是藍色,黃色,綠色,紅色。 enter image description here是否可以忽略Matplotlib繪圖的第一個默認顏色?

然後,我只繪製矩陣a[:,1:4]的第二,第三,第四列。是否有可能使Matplotlib忽略默認的藍色並從黃色開始(這樣我的每一行都會獲得與之前相同的顏色)? enter image description here

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() 

回答

2

爲了使用

plt.rcParams['axes.prop_cycle'].by_key()['color'] 
跳過第一顏色我會建議得到當前顏色列表

this問題所示。然後通過設置當前軸的顏色週期:

plt.gca().set_color_cycle() 

因此您完整的例子是:

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

+0

使用['set_color_cycle'(HTTPS的:// matplotlib。 org/api/_as_gen/matplotlib.axes.Axes.set_color_cycle.html#matplotlib.axes.Axes.set_color_cycle)從版本2.0開始已棄用。它應該由['set_prop_cycle'](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_prop_cycle.html#matplotlib.axes.Axes.set_prop_cycle)取代。 – ImportanceOfBeingErnest

0

您可以調用ax.plot(a[:,1:4])前插入到ax.plot([],[])一個額外的電話。

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() 
0

我有一個印象,你想確保每個colone保持一個定義的顏色。要做到這一點,您可以創建一個顏色矢量,以匹配要顯示的每一列。您可以創建一個顏色矢量。顏色=「藍」,「黃」,「綠」,「紅」]

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() 
3

用於連續行的顏色ar e來自色譜儀的。 爲了跳過這個顏色週期顏色,你可以叫

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

完整的例子看起來像:

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() 
相關問題