更改散点图的颜色

时间:2019-04-27 18:19:31

标签: python pandas matplotlib

找不到我的问题的答案。

我有以下代码生成下面的散点图。

scatter_matrix(iris_ds)
plt.show()

enter image description here

但是,为了区分数据点,我似乎无法更改图中点的颜色。

有什么建议吗?

编辑:为清楚起见-每个散点图框中有3组数据点。我想知道是否有办法:

  • 从蓝色更改颜色?
  • 根据数据点在绘图上的位置更改颜色?

1 个答案:

答案 0 :(得分:2)

如果您查看source of pd.plotting.scatter_matrix

def scatter_matrix(frame, alpha=0.5, figsize=None, ax=None,
               grid=False,
               diagonal='hist', marker='.', density_kwds=None,
               hist_kwds=None, range_padding=0.05, **kwds):  # <---

       [...]

            # Deal with the diagonal by drawing a histogram there.
            if diagonal == 'hist':
               ax.hist(values, **hist_kwds)   # <---  


       [...]

       else:
           common = (mask[a] & mask[b]).values

           ax.scatter(df[b][common], df[a][common],
                       marker=marker, alpha=alpha, **kwds) # <---

您会看到该函数采用**kwds并将其传递给ax.scatter

因此,您可以直接输入颜色:

colors = iris['species'].replace({'setosa':'red', 'virginica': 'green', 'versicolor':'blue'})   

pd.plotting.scatter_matrix(iris, c=colors);

或者您将物种转换为数字,并使用颜色图:

colors = iris['species'].replace({'setosa':1, 'virginica': 2, 'versicolor':3})

pd.plotting.scatter_matrix(iris, c=colors, cmap='viridis');

此外,该函数接受density_kwdshist_kwds,并将它们分别传递给ax.plotax.hist。 因此,您可以通过传递字典来更改直方图的颜色。 kdeplots的同上:

pd.plotting.scatter_matrix(iris, hist_kwds={'color':'red'})