【问题标题】:How to color individual points on scatter plots based on their type using matplotlib如何使用 matplotlib 根据散点图的类型为散点图上的各个点着色
【发布时间】:2018-03-08 14:15:42
【问题描述】:

我正在处理 Iris 数据并尝试使用散点图,虽然我能够获得输出,但我想知道如何使用 matplotlib 根据它们的种类为点着色。

我使用了以下语法:

iris.plot.scatter(x='petal_length', y='petal_width') 
iris.plot(kind='scatter', x='sepal_length', y='sepal_width')

还有什么方法可以使用一行代码为sepal_length/width和petal_length/width创建两个散点图,同时根据物种着色?

【问题讨论】:

  • 我相信你应该有一个名为type 或其他名称的列。只需添加作为参数c='type'
  • 这不是Minimal, Complete, and Verifiable example。请编辑您的问题。话虽如此,IMCoins 可能是对的。但谁知道呢。

标签: python matplotlib jupyter-notebook


【解决方案1】:

在一次调用绘图函数中获得正确的颜色有点乏味。

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

u, inv = np.unique(iris.species.values, return_inverse=True)
ax = iris.plot.scatter(x='petal_length', y='petal_width', 
                  c=inv, cmap="brg", colorbar=False)

plt.show()

因此,我建议循环遍历物种,另外一个优势是能够轻松地将图例放入情节中。

import seaborn as sns
iris = sns.load_dataset("iris")
import matplotlib.pyplot as plt

for n, grp in iris.groupby("species"):
    plt.scatter(grp.petal_length, grp.petal_width, label=n)
plt.legend()
plt.show()

一个简单的解决方案也是使用 seaborn。

import seaborn as sns
iris = sns.load_dataset("iris")
import matplotlib.pyplot as plt

g = sns.FacetGrid(iris, hue="species")
g.map(plt.scatter, 'petal_length','petal_width').add_legend()
plt.show()

【讨论】:

    最近更新 更多