AttributeError: 'ListedColormap' object has no attribute 'get_colors'
时间: 2023-06-23 21:45:41 浏览: 40
非常抱歉,我犯了一个错误。在 Matplotlib 3.4.0 中,`ListedColormap` 对象没有 `get_colors` 方法,可以使用 `colors` 属性代替。你可以尝试以下代码:
```python
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
# 生成 RdYlBu 颜色条
cmap = plt.get_cmap('RdYlBu')
# 将颜色条转换为离散的颜色映射
cmap_discrete = mcolors.ListedColormap(cmap(np.linspace(0, 1, 30)))
# 获取 30 种颜色值
colors = cmap_discrete.colors
# 创建颜色条和刻度
fig, ax = plt.subplots()
cbar = plt.colorbar(ax.imshow(np.arange(30).reshape(1, -1), cmap=cmap_discrete),
orientation='horizontal', ax=ax)
cbar.ax.tick_params(labelsize=8)
cbar.set_ticks(np.arange(0, 30, 5))
cbar.ax.set_xticklabels([f"#{color[0]:02x}{color[1]:02x}{color[2]:02x}" for color in colors[::5]], fontsize=8)
plt.show()
# 输出颜色值的十六进制代码
for color in colors:
print(f"#{color[0]:02x}{color[1]:02x}{color[2]:02x}")
```
这段代码将生成一个包含 30 种颜色的 RdYlBu 颜色条,并输出这些颜色的十六进制代码。同时,它还会显示颜色条和刻度。