我正在用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).
为什么它不起作用,并且有办法解决它吗?
如果有一种简单的方法来生成尺寸的图例,我会使用点的大小而不是颜色
答案 0 :(得分:8)
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返回中获取可映射的东西(由scatter创建的集合),并指定您想要一个用于mappable的颜色条。请注意我的TODO评论,如果您计划通过对图表的其他更改来运行此评论。
outpathc = out.get_children()[3]
#TODO -- don't assume PathCollection is 4th; at least check type
plt.colorbar(mappable=outpathc)
plt.show()
答案 1 :(得分:8)
另一种方法是
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")
答案 2 :(得分: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')