Matplotlib 在颜色之间带有刻度标签的离散颜色栏

Matplotlib 在颜色之间带有刻度标签的离散颜色栏,matplotlib,colorbar,Matplotlib,Colorbar,我试图用一个离散的颜色条绘制一些数据。我遵循了给出的示例(),但问题是这个示例不能以不同的间距1-1工作。例如,链接示例中的间距仅增加1,但我的数据增加了0.5。您可以从我的代码中看到输出。。在此方面的任何帮助都将不胜感激。我知道我丢失了一些关键的东西,但我无法找到它 import matplotlib.pylab as plt import numpy as np def discrete_cmap(N, base_cmap=None): """Create an N-bin dis

我试图用一个离散的颜色条绘制一些数据。我遵循了给出的示例(),但问题是这个示例不能以不同的间距1-1工作。例如,链接示例中的间距仅增加1,但我的数据增加了0.5。您可以从我的代码中看到输出。。在此方面的任何帮助都将不胜感激。我知道我丢失了一些关键的东西,但我无法找到它

import matplotlib.pylab as plt
import numpy as np

def discrete_cmap(N, base_cmap=None):
    """Create an N-bin discrete colormap from the specified input map"""

    # Note that if base_cmap is a string or None, you can simply do
    #    return plt.cm.get_cmap(base_cmap, N)
    # The following works for string, None, or a colormap instance:

    base = plt.cm.get_cmap(base_cmap)
    color_list = base(np.linspace(0, 1, N))
    cmap_name = base.name + str(N)
    return base.from_list(cmap_name, color_list, N)
num=11

x = np.random.randn(40)
y = np.random.randn(40)
c = np.random.randint(num, size=40)


plt.figure(figsize=(10,7.5))

plt.scatter(x, y, c=c, s=50, cmap=discrete_cmap(num, 'jet'))
plt.colorbar(ticks=np.arange(0,5.5,0.5))
plt.clim(-0.5, num - 0.5)
plt.show()

好的,这就是我为我自己的问题找到的黑客。我相信有更好的方法可以做到这一点,但这对我现在所做的工作是有效的。请随意提出更好的方法

import numpy as np
import matplotlib.pylab as plt

def discrete_cmap(N, base_cmap=None):
    """Create an N-bin discrete colormap from the specified input map"""

    # Note that if base_cmap is a string or None, you can simply do
    #    return plt.cm.get_cmap(base_cmap, N)
    # The following works for string, None, or a colormap instance:

    base = plt.cm.get_cmap(base_cmap)
    color_list = base(np.linspace(0, 1, N))
    cmap_name = base.name + str(N)
    return base.from_list(cmap_name, color_list, N)

num=11

plt.figure(figsize=(10,7.5))

x = np.random.randn(40)
y = np.random.randn(40)
c = np.random.randint(num, size=40)


plt.scatter(x, y, c=c, s=50, cmap=discrete_cmap(num, 'jet'))
cbar=plt.colorbar(ticks=range(num))
plt.clim(-0.5, num - 0.5)
cbar.ax.set_yticklabels(np.arange(0.0,5.5,0.5))
plt.show()
由于某些原因,我无法上传与上述代码关联的图像。我上传时出错,因此不确定如何显示最后的示例。但我只需为垂直颜色栏的勾号标签设置颜色栏轴,并传入我想要的标签,它就产生了正确的输出。

不确定matplotlib/pyplot的哪个版本引入了此功能,但
plt.get\u cmap
现在支持一个
int
参数,指定离散颜色贴图要获取的颜色数。 这会自动导致颜色栏离散。 顺便说一句,
pandas
对色条的处理甚至更好

import numpy as np
from matplotlib import pyplot as plt
plt.style.use('ggplot')
# remove if not using Jupyter/IPython
%matplotlib inline

# choose number of clusters and number of points in each cluster
n_clusters = 5
n_samples = 20

# there are fancier ways to do this
clusters = np.array([k for k in range(n_clusters) for i in range(n_samples)])

# generate the coordinates of the center 
# of each cluster by shuffling a range of values
clusters_x = np.arange(n_clusters)
clusters_y = np.arange(n_clusters)

np.random.shuffle(clusters_x)
np.random.shuffle(clusters_y)

# get dicts like cluster -> center coordinate
x_dict = dict(enumerate(clusters_x))
y_dict = dict(enumerate(clusters_y))

# get coordinates of cluster center for each point
x = np.array(list(x_dict[k] for k in clusters)).astype(float)
y = np.array(list(y_dict[k] for k in clusters)).astype(float)

# add noise
x += np.random.normal(scale=0.5, size=n_clusters*n_samples)
y += np.random.normal(scale=0.5, size=n_clusters*n_samples)

### Finally, plot
fig, ax = plt.subplots(figsize=(12,8))

# get discrete colormap
cmap = plt.get_cmap('viridis', n_clusters)

# scatter points
scatter = ax.scatter(x, y, c=clusters, cmap=cmap)

# scatter cluster centers
ax.scatter(clusters_x, clusters_y, c='red')

# add colorbar
cbar = plt.colorbar(scatter)

# set ticks locations (not very elegant, but it works):
# - shift by 0.5
# - scale so that the last value is at the center of the last color
tick_locs = (np.arange(n_clusters) + 0.5)*(n_clusters-1)/n_clusters
cbar.set_ticks(tick_locs)

# set tick labels (as before)
cbar.set_ticklabels(np.arange(n_clusters))

单凭代码不足以理解您想要实现的目标。你能准确地告诉结果颜色条在颜色、颜色数量、标签数量、标签数量方面应该是什么样子吗?!我只是希望记号标签与它们的颜色相关联。例如,每个记号标签应位于其相应颜色之间。颜色数=勾号标签的数量。您可以选择11种颜色,其值从0到10。它们分布在从蓝色到红色的颜色范围内。如果现在选择0到5.5之间的ticklabels,则此范围中只有一半会有ticklabel。这是很合乎逻辑的。然而,你似乎对此不满意。那么问题又来了:在颜色、颜色数量、标签数量、标签数量方面,最终的颜色条应该是什么样的呢。这与数据(在0到10之间)有什么关系?请看下面我的答案。这对我来说没有意义。例如,深红色点的数据值为10,但颜色栏显示的值为5.5。因此,对于观看它的人来说,这是完全令人困惑的。我刚刚用正确的代码上传了正确的绘图。这就是我希望颜色栏的外观。我昨天的评论仍然适用-颜色栏只是显示了错误的值。如果这是你想要的,很好。注意色条上的记号位置不正确。不管怎样,要像我所展示的那样在颜色的中心画上记号?@CharanjitPabla这就是你要找的吗?