“连续”色彩图
如果你想循环浏览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
属性,所以这仅适用于那些颜色图,但不适用于例如这jet
map.
组合解决方案
以下是一个通用函数,它将颜色图作为输入并输出相应的循环器。我最初提出这个解决方案这个 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)
“连续”情况的用法:
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()