Python散点图:如何使用与颜色周期具有相同颜色的颜色图

时间:2019-02-21 16:17:29

标签: python matplotlib scatter-plot graph-coloring

我正在尝试为散点图中的群集着色,并且使用两种不同的方法进行管理。

在第一个步骤中,我迭代绘制每个群集,在第二个步骤中,我一次绘制所有数据,并根据群集的标签[0、1、2、3、4]为其着色。

我对在example1example3中获得的结果感到满意,但是我不明白为什么在根据标签为群集着色时,为什么颜色变化如此之大,而不是反复绘制每个群集。

另外,为什么第二个簇(尽管始终带有标签“ 1”)在example1和example3中具有不同的颜色?

import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight') #irrelevant here, but coherent with the examples=)

fig, ax = plt.subplots(figsize=(6,4))
for clust in range(kmeans.n_clusters):
    ax.scatter(X[kmeans.labels_==clust],Y[kmeans.labels_==clust])
    ax.set_title("example1")`

example1

plt.figure(figsize = (6, 4))
plt.scatter(X,Y,c=kmeans.labels_.astype(float))
plt.title("example2")

example2

(我知道我可以为第二种方法显式定义一个颜色图,但是在示例1中找不到能重现结果的任何颜色)

这是一个最小的工作示例

import matplotlib.pyplot as plt
import pandas as pd
plt.style.use('fivethirtyeight') #irrelevant here, but coherent with the examples=)
X=pd.Series([1, 2, 3, 4, 5, 11, 12, 13, 14, 15])
Y=pd.Series([1,1,1,1,1,2,2,2,2,2])
clusters=pd.Series([0,0,0,0,0,1,1,1,1,1])


fig, ax = plt.subplots(figsize=(6,4))
for clust in range(2):
ax.scatter(X[clusters==clust],Y[clusters==clust])
ax.set_title("example3")

example3

plt.figure(figsize = (6, 4))
plt.scatter(X,Y, c=clusters)
plt.title("example4")

example4

1 个答案:

答案 0 :(得分:3)

当您在群集上循环并绘制scatter而不指定任何颜色时,将使用活动属性循环程序的默认颜色(颜色循环)。活动属性循环程序在rcParams中定义。通过使用的样式进行设置;您的情况下,使用'fivethirtyeight'

print(plt.rcParams["axes.prop_cycle"])
> cycler('color', ['#008fd5', '#fc4f30', '#e5ae38', '#6d904f', '#8b8b8b', '#810f7c'])

此图形的前两种颜色(“#008fd5”,“#fc4f30”)是您在图中看到的颜色。

当您使用带有scatter作为颜色参数的clusters时,这些值将通过颜色图映射到颜色。如果未指定颜色图,它将采用rcParam中定义的默认颜色图。

print(plt.rcParams["image.cmap"])
> "viridis"

'fivethirtyeight'样式没有定义任何特殊的颜色图,因此默认值将保持不变。 (事实上​​,您在图片中观察到的颜色与viridis不同,这是由于存在其他一些仍处于活动状态的代码未在问题中显示的事实。)

这时我需要开始翻译;我想您的问题确实是如何使用颜色与颜色循环相同的颜色图来获得单个散点图。预定义的颜色图均未包含第五十八个循环器颜色。因此,您可以通过taking the colors from the cycle

手动定义该颜色图。
import matplotlib.colors as mcolors
cmap = mcolors.ListedColormap(plt.rcParams['axes.prop_cycle'].by_key()['color'])

现在您需要一种索引颜色表的方法,因为您有离散的簇。

n = len(clusters.unique())
norm = mcolors.BoundaryNorm(np.arange(n+1)-0.5, n)

当然,这需要颜色图中的颜色数量大于或等于类的数量-在这里就是这种情况。

将它们放在一起,(我添加了另一个类别,以使其更具说明性)

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.colors as mcolors

plt.style.use('fivethirtyeight') #relevant here!!

X=pd.Series([1, 2, 3, 4, 5, 11, 12, 13, 14, 15])
Y=pd.Series([1,1,1,1,1,2,2,2,2,2])
clusters=pd.Series([0,0,0,0,0,1,1,1,1,2])

cmap = mcolors.ListedColormap(plt.rcParams['axes.prop_cycle'].by_key()['color'])
n = len(clusters.unique())
norm = mcolors.BoundaryNorm(np.arange(n+1)-0.5, n)

plt.figure(figsize = (6, 4))
sc = plt.scatter(X,Y, c=clusters, cmap=cmap, norm=norm)
plt.colorbar(sc, ticks=clusters.unique())
plt.title("example4")

plt.show()

enter image description here