将颜色条作为图例添加到matplotlib散点图(多个子图,多个散点) [英] Add colorbar as legend to matplotlib scatterplot (multiple subplots, multiple scatters)

查看:1139
本文介绍了将颜色条作为图例添加到matplotlib散点图(多个子图,多个散点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个要添加单个颜色条的子图.每个子图由7个散点组成.我发现了有关如何添加颜色条的建议,但它们主要与每个散点的值有关,而与行本身无关.

I have several subplots to which I want to add a single colorbar. Each subplot consists of 7 scatters. I found advise on how to add colorbars, but they are mostly related to the value of each scatter-point and not to the row itself.

代表性示例代码:

import numpy as np
from matplotlib import pyplot as plt

x = range(50)
scales = np.linspace(0, 2, 7)
locs = range(4)
cmap = plt.get_cmap("Spectral")
for s_plot in range(4):
    plt.subplot(2, 2, s_plot+1)
    color = iter(cmap(np.linspace(0, 1, len(scales))))
    for scale in scales:
        c = next(color)
        y = np.random.normal(loc=locs[s_plot], scale=scale, size=50)
        plt.scatter(x, y, c=c, s=5)
        plt.title("Mean = {:d}".format(locs[s_plot]))
plt.subplots_adjust(hspace=0.4)
plt.show()

以上示例给出:

我想要的颜色条看起来像这样(假的,要放在图的旁边):

My desired colorbar looks like this (fake, to be placed next to the plot):

因此,颜色栏并没有描述我的分散点的值,而是描述了经过迭代的不同行"(在本例中为不同的比例).在该示例中,这将有助于将点与比例尺匹配.

So the colorbar does not depict the value of my scatterpoints, but rather the different "rows" (in this case: different scales) that are iterated through. In the example that would help match the points to the scales.

我尝试过的很简单

plt.colorbar()

,在完成每个子图后将调用一次.但是我明白了 TypeError: You must first set_array for mappable 另外,由于是我要为其创建颜色图的不同比例,因此我也尝试了

which is called once after finishing each subplot. But I get TypeError: You must first set_array for mappable Also, since it is the different scales I want to create the colormap for, I also tried

plt.colorbar(scales) 

返回:AttributeError: 'numpy.ndarray' object has no attribute 'autoscale_None'.

我目前对如何进行此操作缺乏方向. 我被标记为 matplotlib颜色条的可能重复.我已经找到了这个问题,但是对我的问题没有帮助.在我的情况下,我需要一个独立于z值的色图,但仅表示行号"或散点行",或者您要调用它(等同于plt.plot中的行" ).

I am currently lacking orientation on how to proceed on this. I was marked as possible duplicate of matplotlib colorbar for scatter. I found that question already, but it didn't help with my problem. In my case, I need a colormap that is independent of a z-value, but will only indicate the "row number" or "scatter-row" or however you want to call it (equivalent to "lines" in a plt.plot).

推荐答案

颜色条需要ScalarMappable作为输入.因此,如果您在绘图中创建的所有内容均不适合此操作,则可以自己创建.

A colorbar needs a ScalarMappable as input. So if none of the things you create in your plot is suitable for that, you may create it yourself.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.cm import ScalarMappable

x = range(50)
scales = np.linspace(0, 2, 7)
locs = range(4)
cmap = plt.get_cmap("Spectral")
norm = plt.Normalize(scales.min(), scales.max())

fig, axes = plt.subplots(2,2, constrained_layout=True, sharey=True)

for s_plot, ax in enumerate(axes.flat):
    for scale in scales:
        y = np.random.normal(loc=locs[s_plot], scale=scale, size=50)
        sc = ax.scatter(x, y, c=[cmap(norm(scale))], s=5)
        ax.set_title("Mean = {:d}".format(locs[s_plot]))

sm =  ScalarMappable(norm=norm, cmap=cmap)
sm.set_array([])
cbar = fig.colorbar(sm, ax=axes[:,1])
cbar.ax.set_title("scale")

plt.show()

这篇关于将颜色条作为图例添加到matplotlib散点图(多个子图,多个散点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆