具有点颜色的散点图代表Seaborn FacetGrid中的连续变量 [英] Scatterplot with point colors representing a continuous variable in seaborn FacetGrid

查看:90
本文介绍了具有点颜色的散点图代表Seaborn FacetGrid中的连续变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python中的seaborn生成多面板图形,我希望多面板图形中点的颜色由连续变量指定.这是我尝试处理"iris"数据集的一个示例:

I am trying to generate multi-panel figure using seaborn in python and I want the color of the points in my multi-panel figure to be specified by a continuous variable. Here's an example of what I am trying to do with the "iris" dataset:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')

g = sns.FacetGrid(iris, col = 'species', hue = 'petal_length', palette = 'seismic')
g = g.map(plt.scatter, 'sepal_length', 'sepal_width', s = 100, alpha = 0.5)
g.add_legend()

如下图所示:

哪个很好,但是传说太长了.我想抽样这些值的1/4(理想情况下),或者禁止显示颜色条的条纹. 例如,像这样的东西可能是可以接受的,但我仍然希望将其分为三个种类.

Which is nice, but the legend is way too long. I'd like to sample out like 1/4 of these values (ideally) or barring that display a colorbar instead. For instance, something like this might be acceptable, but I'd still want to split it over the three species.

plt.scatter(iris.sepal_length, iris.sepal_width, alpha = .8, c = iris.petal_length, cmap = 'seismic')
cbar = plt.colorbar()

关于如何充分利用这两个情节的任何想法?

Any idea about how I can get the best of both of these plots?

这个话题似乎是一个好的开始.

This topic seems like a good start.

https://github.com/mwaskom/seaborn/issues/582

对于该用户,以某种方式,在其他所有内容都运行完之后,简单地添加plt.colorbar似乎可以正常工作.不过,在这种情况下似乎没有帮助.

Somehow, for this user, simply appending plt.colorbar after everything else ran seemed to somehow work. Doesn't seem to help in this case though.

推荐答案

由于您正在询问散点图例,因此可以使用@mwaskom的解决方案来生成具有散点的图例,如下所示:

Since you were asking about a legend for the scatter, one may adapt @mwaskom's solution to produce a legend with scatter points like so:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')

g = sns.FacetGrid(iris, col='species', palette = 'seismic')

def facet_scatter(x, y, c, **kwargs):
    kwargs.pop("color")
    plt.scatter(x, y, c=c, **kwargs)

vmin, vmax = 0, 7
cmap = plt.cm.viridis

norm=plt.Normalize(vmin=vmin, vmax=vmax)

g = g.map(facet_scatter, 'sepal_length', 'sepal_width', "petal_length",
          s=100, alpha=0.5, norm=norm, cmap=cmap)

# Make space for the colorbar
g.fig.subplots_adjust(right=.9)

lp = lambda i: plt.plot([], color=cmap(norm(i)), marker="o", ls="", ms=10, alpha=0.5)[0]
labels = np.arange(0,7.5,0.5)
h = [lp(i) for i in labels]
g.fig.legend(handles=h, labels=labels, fontsize=9)

plt.show()

这篇关于具有点颜色的散点图代表Seaborn FacetGrid中的连续变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆