带有颜色条的 Seaborn regplot?

Seaborn regplot with colorbar?

我正在用 seaborn 的 regplot 策划一些事情。据我了解,它在幕后使用 pyplot.scatter 。所以我假设如果我将散点图的颜色指定为一个序列,那么我就可以调用 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).

为什么它不起作用,有解决办法吗?


如果有一种简单的方法来为尺寸生成图例,我可以使用点的尺寸而不是颜色

regplot 的颜色参数将单一颜色应用于 regplot 元素(这在 seaborn 文档中)。控制散点图需要通过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'})

然后你从 AxesSubplot seaborn returns 中得到可映射的东西(由 scatter 制作的集合),并指定你想要一个可映射的颜色条。请注意我的 TODO 评论,如果您打算 运行 这与情节的其他更改。

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

plt.colorbar(mappable=outpathc)

plt.show()

另一种方法是

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

事实上,您可以简单地访问 seaborn 图的图形对象并使用其 colorbar() 函数手动添加颜色条。我发现这种方法好多了。

此代码生成附加图:

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