How to add colorbars to scatterplots created like this?

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

    The answer to this can be to only plot a single scatter, which would then directly allow for a colobar to be created. This involves putting the markers into the PathCollection created by the scatter a posteriori, but it can be easily placed in a function. This function comes from my answer on another question, but is directly applicable here.

    Taking the data from @PaulH's post this would look like

    import numpy as np    
    import pandas as pd
    import matplotlib.pyplot as plt
    
    def mscatter(x,y,ax=None, m=None, **kw):
        import matplotlib.markers as mmarkers
        ax = ax or plt.gca()
        sc = ax.scatter(x,y,**kw)
        if (m is not None) and (len(m)==len(x)):
            paths = []
            for marker in m:
                if isinstance(marker, mmarkers.MarkerStyle):
                    marker_obj = marker
                else:
                    marker_obj = mmarkers.MarkerStyle(marker)
                path = marker_obj.get_path().transformed(
                            marker_obj.get_transform())
                paths.append(path)
            sc.set_paths(paths)
        return sc
    
    
    markers = ['s', 'o', '^']
    records = []
    for n in range(37):
        records.append([np.random.normal(), np.random.normal(), np.random.normal(), 
                        markers[np.random.randint(0, high=3)]])
    
    records = pd.DataFrame(records, columns=['x', 'y', 'z', 'marker'])
    
    fig, ax = plt.subplots()
    sc = mscatter(records.x, records.y, c=records.z, m=records.marker, ax=ax)
    fig.colorbar(sc, ax=ax)
    
    plt.show()
    

提交回复
热议问题