简体   繁体   English

使用离散刻度获取 matplotlib 中散点图的颜色条

[英]Get color bar for scatter plot in matplotlib with discrete ticks

I would like to to get a scatter plot with color bar having discrete ticks that bound each of the colors used.我想得到一个散点图,颜色条具有离散的刻度,这些刻度限制了所使用的每种颜色。 Presently, the following code merges top two colors.目前,以下代码合并了前两种颜色。

import numpy as np
np.random.seed(42)
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

a1 = np.random.randint(-100, 100, 10)
a2 = np.random.randint(-100, 100, 10)

fig = plt.figure(figsize=(5, 5))

limits1 = [min(a2), max(a2)]
bounds1 = np.linspace(limits1[0], limits1[1], 5)
colors1 = plt.get_cmap('jet')(np.linspace(0, 1, len(bounds1)))
cmap1 = mcolors.ListedColormap(colors1[1:-1])
norm1 = mcolors.BoundaryNorm(boundaries=bounds1, ncolors=len(bounds1)-1)

ax1 = fig.add_subplot(1, 1, 1)
im1 = ax1.scatter(a1, a2, c=a2, norm=norm1, cmap=cmap1)
fig.colorbar(im1, orientation='vertical', shrink=1, aspect=30, pad=0.03, extend='neither', ticks=bounds1, label='ampWT')

plt.show()

在此处输入图片说明

when running this line:运行此行时:

cmap1 = mcolors.ListedColormap(colors1[1:-1])

You're effectively removing the first and last colors from the colors1 list.您有效地从colors1 列表中删除了第一个和最后一个颜色。 Since you started with 5 colors (bounds1 is length 5) you're left with 3 colors, which explains why you don't have the correct number of colors.由于您从 5 种颜色开始(bounds1 的长度为 5),因此您只剩下 3 种颜色,这解释了为什么您没有正确数量的颜色。

If you want to fix it you have 2 solutions:如果你想修复它,你有两个解决方案:

  1. just add another color in the beginning to have 6 initial colors and remove 2只需在开头添加另一种颜色即可获得 6 个初始颜色并删除 2 个
bounds1 = np.linspace(limits1[0], limits1[1], 5)
colors1 = plt.get_cmap('jet')(np.linspace(0, 1, len(bounds1)+1)) # add 1 color 
cmap1 = mcolors.ListedColormap(colors1[1:-1])
norm1 = mcolors.BoundaryNorm(boundaries=bounds1, ncolors=len(bounds1))
  1. choose the final number of colors from the beginning (4)从一开始就选择最终的颜色数 (4)
bounds1 = np.linspace(limits1[0], limits1[1], 5)
colors1 = plt.get_cmap('jet')(np.linspace(0, 1, len(bounds1)-1)) # changed length of colors
cmap1 = mcolors.ListedColormap(colors1) # changed colors input
norm1 = mcolors.BoundaryNorm(boundaries=bounds1, ncolors=len(colors1)) # changed ncolors

The final colors are not the same, so pick the one you prefer最终的颜色不一样,所以选择你喜欢的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM