How to add colorbars to scatterplots created like this?

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

    I think your best bet will be to stuff your data into a pandas dataframe, and loop through all of your markers like so:

    import numpy as np    
    import pandas as pd
    import matplotlib.pyplot as plt
    
    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()
    for m in np.unique(records.marker):
        selector = records.marker == m
        s = ax.scatter(records[selector].x, records[selector].y, c=records[selector].z,
                       marker=m, cmap=plt.cm.coolwarm, 
                       vmin=records.z.min(), vmax=records.z.max())
    
    cbar = plt.colorbar(mappable=s, ax=ax)
    cbar.set_label('My Label')
    

    resuling graph

提交回复
热议问题