How to add colorbars to scatterplots created like this?

前端 未结 4 682
我寻月下人不归
我寻月下人不归 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:35

    I think this should do the trick. I'm pretty sure I grabbed this from one of the matplotlib cookbook examples a while back, but I can't seem to find it now...

    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    cmap = (matplotlib.color.LinearSegmentedColormap.
            from_list('blueWhiteRed', ['blue', 'white', 'red']))
    
    fig = matplotlib.figure.Figure(figsize=(4, 4), dpi=72)
    ax = fig.gca()
    
    for record in data:
        level = record.level # a float in [0.0, 1.0]
        ax.scatter(record.x, record.y,
                   c=level, vmin=0, vmax=1, cmap=cmap, **otherkwargs)
    
    # various settings of ticks, labels, etc. omitted
    
    divider= make_axes_locatable(ax)
    cax = divider.append_axes("right", size="1%", pad=0.05)
    cb = plt.colorbar(cax=cax)
    cb.set_label('Cbar Label Here')
    
    canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
    fig.set_canvas(canvas)
    canvas.print_png('/path/to/output/fig.png')
    

提交回复
热议问题