How to add colorbars to scatterplots created like this?

前端 未结 4 686
我寻月下人不归
我寻月下人不归 2020-12-11 03:52

I create scatterplots with code that, in essence, goes like this

cmap = (matplotlib.color.LinearSegmentedColormap.
        from_list(\'blueWhiteRed\', [\'blu         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 04:37

    If you have to use a different marker for each set, you have to do a bit of extra work and force all of the clims to be the same (otherwise they default to scaling from the min/max of the c data per scatter plot).

    from pylab import *
    import matplotlib.lines as mlines
    import itertools
    fig = gcf()
    ax = fig.gca()
    
    # make some temorary arrays
    X = []
    Y = []
    C = []
    cb = None
    # generate fake data
    markers = ['','o','*','^','v']
    cmin = 0
    cmax = 1
    for record,marker in itertools.izip(range(5),itertools.cycle(mlines.Line2D.filled_markers)):
        x = rand(50)
        y = rand(50)
        c = rand(1)[0] * np.ones(x.shape)
        if cb is None:
            s = ax.scatter(x,y,c=c,marker=markers[record],linewidths=0)
            s.set_clim([cmin,cmax])
            cb = fig.colorbar(s)
        else:
            s = ax.scatter(x,y,c=c,marker=markers[record],linewidths=0)
            s.set_clim([cmin,cmax])
    
    cb.set_label('Cbar Label Here')
    

    thelinewidths=0 sets the width of the border on the shapes, I find that for small shapes the black border can overwhelm the color of the fill.

    colored scatter plot

    If you only need one shape you can do this all with a single scatter plot, there is no need to make a separate one for each pass through your loop.

    from pylab import *
    fig = gcf()
    ax = fig.gca()
    
    # make some temorary arrays
    X = []
    Y = []
    C = []
    # generate fake data
    for record in range(5):
        x = rand(50)
        y = rand(50)
        c = rand(1)[0] * np.ones(x.shape)
        print c
        X.append(x)
        Y.append(y)
        C.append(c)
    
    X = np.hstack(X)
    Y = np.hstack(Y)
    C = np.hstack(C)
    

    once you have the data all beaten down into a 1D array, make the scatter plot, and keep the returned value:

    s = ax.scatter(X,Y,c=C)
    

    You then make your color bar and pass the object returned by scatter as the first argument.

    cb = plt.colorbar(s)
    cb.set_label('Cbar Label Here')
    

    You need do this so that the color bar knows which color map (both the map and the range) to use.

    enter image description here

提交回复
热议问题