Seaborn regplot with colorbar?

后端 未结 3 1841
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 17:06

I\'m plotting something with seaborn\'s regplot. As far as I understand, it uses pyplot.scatter behind the scenes. So I assumed that if I specify c

相关标签:
3条回答
  • 2020-12-30 17:09

    Another approach would be

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    tips = sns.load_dataset("tips")
    
    points = plt.scatter(tips["total_bill"], tips["tip"],
                         c=tips["size"], s=75, cmap="BuGn")
    plt.colorbar(points)
    
    sns.regplot("total_bill", "tip", data=tips, scatter=False, color=".1")
    

    enter image description here

    0 讨论(0)
  • 2020-12-30 17:10

    The color argument to regplot applies a single color to regplot elements (this is in the seaborn documentation). To control the scatterplot, you need to pass kwargs through:

    import pandas as pd
    import seaborn as sns
    import numpy.random as nr
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    data = nr.random((9,3))
    df = pd.DataFrame(data, columns=list('abc'))
    out = sns.regplot('a','b',df, scatter=True,
                      ax=ax,
                      scatter_kws={'c':df['c'], 'cmap':'jet'})
    

    Then you get the mappable thing (the collection made by scatter) out of the AxesSubplot seaborn returns, and specify that you want a colorbar for the mappable. Note my TODO comment, if you plan to run this with other changes to the plot.

    outpathc = out.get_children()[3] 
    #TODO -- don't assume PathCollection is 4th; at least check type
    
    plt.colorbar(mappable=outpathc)
    
    plt.show()
    

    enter image description here

    0 讨论(0)
  • 2020-12-30 17:10

    As a matter of fact you can simply access the seaborn plot's figure object and use its colorbar() function to add a colorbar manually. I find this approach much better.

    This code produces the attached plot:

    import seaborn as sns
    import matplotlib.pyplot as plt
    tips = sns.load_dataset("tips")
    sns.scatterplot(tips["total_bill"], tips["tip"],
                         hue=tips["size"], s=75, palette="BuGn", legend=False)
    reg_plot=sns.regplot("total_bill", "tip", data=tips, scatter=False, color=".1")
    reg_plot.figure.colorbar(mpl.cm.ScalarMappable([![enter image description here][1]][1]norm=mpl.colors.Normalize(vmin=0, vmax=tips["size"].max(), clip=False), cmap='BuGn'),label='tip size')
    

    The plot from the above code

    0 讨论(0)
提交回复
热议问题