我想创建一个散点图的FacetGrid,其中点的颜色由绘制的数据框中的一列定义。但是,似乎在映射时无法将列名传递给c=
的plt.scatter
参数,因为它被解释为比列名更刺耳的颜色字符串:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style='white')
iris = sns.load_dataset('iris')
g = sns.FacetGrid(iris, row='species', size=4)
g.map(plt.scatter, 'sepal_width', 'sepal_length', c='petal_length')
出:
/home/user/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba_array(self, c, alpha)
420 result = np.zeros((nc, 4), dtype=np.float)
421 for i, cc in enumerate(c):
--> 422 result[i] = self.to_rgba(cc, alpha)
423 return result
424
/home/user/anaconda/lib/python2.7/site-packages/matplotlib/colors.pyc in to_rgba(self, arg, alpha)
374 except (TypeError, ValueError) as exc:
375 raise ValueError(
--> 376 'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
377
378 def to_rgba_array(self, c, alpha=None):
ValueError: to_rgba: Invalid rgba arg "p"
to_rgb: Invalid rgb arg "p"
could not convert string to float: p
我预期的结果与
plt.scatter(iris.sepal_width, iris.sepal_length, c=iris.petal_length)
中的结果相同我曾短暂尝试过
sns.regplot
,但似乎遇到了同样的问题。如果未指定FacetGrid的row=
或col=
参数,则可以输入c=iris.petal_length
以获得预期的结果。有没有一种创建FacetGrid的方法,其中按行或列对数据进行分组,并根据数据框中的列对数据点进行着色?
最佳答案
您可以通过指定hue
参数来实现。
g = sns.FacetGrid(iris, col='species', hue='petal_length', size=4)
g.map(plt.scatter, 'sepal_width', 'sepal_length')
生成此图:。