使用matplotlib中会遇到选择颜色的问题,很多人会觉得自带的matlab风格的颜色不好看。好在Matplotlib已经预见到了这个问题,除了支持最基本的matlab传统颜色之外,还支持很多种颜色的表达方式:
- RGB 或者 RGBA 浮点值元组,[0, 1]之间,例如(0.1, 0.2, 0.5)或者(0.1, 0.2, 0.5, 0.3)。
- RGB 或者 RGBA 十六进制字符串,例如#0F0F0F或者#0F0F0F0F。
- [0, 1]之间的浮点值的字符串表示,用于表示灰度,例如0.5。
- {‘b’, ‘g’, ‘r’, ‘c’, ‘m’, ‘y’, ‘k’, ‘w’}之一。
- XKCD 颜色之一,以’xkcd:‘为前缀,例如’xkcd:sky blue’。
- matplotlib 默认的十色环{‘C0’, ‘C1’, ‘C2’, ‘C3’, ‘C4’, ‘C5’, ‘C6’, ‘C7’, ‘C8’, ‘C9’}之一。这是 matplotlib 绘图默认依次使用的颜色。
- 十色环的另一种形式{‘tab:blue’, ‘tab:orange’, ‘tab:green’, ‘tab:red’, ‘tab:purple’, ‘tab:brown’, ‘tab:pink’, ‘tab:gray’, ‘tab:olive’, ‘tab:cyan’}之一。这是 T10 调色板的 Tableau 颜色(默认的色相环)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
th = np.linspace(0, 2*np.pi, 128)
def demo(sty):
mpl.style.use(sty)
fig, ax = plt.subplots(figsize=(3, 3))
ax.set_title('style: {!r}'.format(sty), color='C0')
ax.plot(th, np.cos(th), 'tab:blue', label='C1')
ax.plot(th, np.sin(th), 'tab:red', label='C2')
ax.legend()
demo('default')
demo('seaborn')