Seaborn regplot with colorbar?

17,150

Solution 1

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

Solution 2

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

Solution 3

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

Share:
17,150
Phlya
Author by

Phlya

Molecular biologist interested in bioinformatics. Use python in my work, especially numpy, pandas, matplotlib, seaborn.

Updated on July 03, 2022

Comments

  • Phlya
    Phlya almost 2 years

    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 colour for scatterplot as a sequence, I would then be able to just call plt.colorbar, but it doesn't seem to work:

    sns.regplot('mapped both', 'unique; repeated at least once', wt, ci=95, logx=True, truncate=True, line_kws={"linewidth": 1, "color": "seagreen"}, scatter_kws={'c':wt['Cis/Trans'], 'cmap':'summer', 's':75})
    plt.colorbar()
    
    Traceback (most recent call last):
    
      File "<ipython-input-174-f2d61aff7c73>", line 2, in <module>
        plt.colorbar()
    
      File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 2152, in colorbar
        raise RuntimeError('No mappable was found to use for colorbar '
    
    RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).
    

    Why doesn't it work, and is there a way around it?


    I would be fine with using size of the dots instead of colour if there was an easy way to generate a legend for the sizes

  • mwaskom
    mwaskom almost 9 years
    Good answer, but shame on you for using the jet colormap in a seaborn plot :)
  • cphlewis
    cphlewis almost 9 years
    Pedagogical! It's so clear it's a colormap and not seaborn's doing. ...Ugly and not helpful to the colorblind, though.
  • Phlya
    Phlya almost 9 years
    Thank you, @mwaskom! Shame on me for not figuring this out! I guess I'm assuming all-powerness of seaborn too much, and thus don't think of stitching it together with "raw" matplotlib :)
  • Phlya
    Phlya almost 9 years
    Thank you! This is a good option, but I will accept the other one as it makes no assumptions about anything and should work with any data.
  • KLDavenport
    KLDavenport over 8 years
    This is great, but I'm guessing the color method won't convert nominal values to discrete colors. So I'll have to do something like: color_map = {' 36 months': 0, ' 60 months': 1} plot_df['term_color'] = plot_df.term.map(color_map)
  • Nandor Poka
    Nandor Poka almost 4 years
    You can do this in "pure" seaborn. no need to mix in plt scatter and then regplot. In my answer you can use the seaborn scaptterplot and regplot together, and add the colorbar directly to the regplot.
  • Rylan Schaeffer
    Rylan Schaeffer over 2 years
    I think your code has a typo in the middle.
  • Rylan Schaeffer
    Rylan Schaeffer over 2 years
    When I try this, my colorbar is inverted. Do you know how to fix that? stackoverflow.com/questions/70841189/…