简体   繁体   English

带颜色条的 Seaborn regplot?

[英]Seaborn regplot with colorbar?

I'm plotting something with seaborn's regplot .我正在用 seaborn 的regplot绘制一些东西。 As far as I understand, it uses pyplot.scatter behind the scenes.据我了解,它在幕后使用pyplot.scatter 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:所以我假设如果我将散点图的颜色指定为一个序列,那么我就可以只调用plt.colorbar ,但它似乎不起作用:

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如果有一种简单的方法来生成大小的图例,我会很好地使用点的大小而不是颜色

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")

在此处输入图片说明

The color argument to regplot applies a single color to regplot elements (this is in the seaborn documentation). regplot 的 color 参数将单一颜色应用于 regplot 元素(这在 seaborn 文档中)。 To control the scatterplot, you need to pass kwargs through:要控制散点图,您需要通过 kwargs:

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.然后您从 AxesSubplot seaborn 返回中获取可映射的东西(由 scatter 生成的集合),并指定您想要可映射的颜色条。 Note my TODO comment, if you plan to run this with other changes to the plot.请注意我的 TODO 评论,如果您打算在对绘图进行其他更改的情况下运行它。

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

plt.colorbar(mappable=outpathc)

plt.show()

在此处输入图片说明

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.事实上,您可以简单地访问 seaborn 绘图的图形对象并使用其colorbar()函数手动添加颜色条。 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')

上面代码的情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM