“连续”色图
如果您想从“连续”的色图中循环使用N
种颜色,例如默认的viridis色图,则@Gerges的解决方案非常好用。
import matplotlib.pyplot as plt
N = 6
plt.rcParams["axes.prop_cycle"] = plt.cycler("color", plt.cm.viridis(np.linspace(0,1,N)))
fig, ax = plt.subplots()
for i in range(N):
ax.plot([0,1], [i, 2*i])
plt.show()
"离散" 的颜色映射
Matplotlib提供了一些颜色映射,它们在定性视觉方面是“离散”的,例如tab10
颜色映射,只保留少量不同的颜色。要循环使用这种颜色映射,解决方法可能是不使用N
,而是将映射中的所有颜色都放入循环器中。
import matplotlib.pyplot as plt
plt.rcParams["axes.prop_cycle"] = plt.cycler("color", plt.cm.tab20c.colors)
fig, ax = plt.subplots()
for i in range(15):
ax.plot([0,1], [i, 2*i])
plt.show()
请注意,只有ListedColormaps
具有.colors
属性,因此此方法仅适用于这些colormap,而不适用于例如jet
地图。
综合解决方案
以下是一个通用函数,它以colormap作为输入并输出相应的cycler。我最初在这个matplotlib问题中提出了这个解决方案。
from matplotlib.pyplot import cycler
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
import matplotlib.cm
def get_cycle(cmap, N=None, use_index="auto"):
if isinstance(cmap, str):
if use_index == "auto":
if cmap in ['Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']:
use_index=True
else:
use_index=False
cmap = matplotlib.cm.get_cmap(cmap)
if not N:
N = cmap.N
if use_index=="auto":
if cmap.N > 100:
use_index=False
elif isinstance(cmap, LinearSegmentedColormap):
use_index=False
elif isinstance(cmap, ListedColormap):
use_index=True
if use_index:
ind = np.arange(int(N)) % cmap.N
return cycler("color",cmap(ind))
else:
colors = cmap(np.linspace(0,1,N))
return cycler("color",colors)
使用"continuous"情况的方法:
import matplotlib.pyplot as plt
N = 6
plt.rcParams["axes.prop_cycle"] = get_cycle("viridis", N)
fig, ax = plt.subplots()
for i in range(N):
ax.plot([0,1], [i, 2*i])
plt.show()
"离散"情况的使用方法
import matplotlib.pyplot as plt
plt.rcParams["axes.prop_cycle"] = get_cycle("tab20c")
fig, ax = plt.subplots()
for i in range(15):
ax.plot([0,1], [i, 2*i])
plt.show()
(
开头,而不是以[(
开头,对吗? - cphlewis