簡體   English   中英

用完全不同的顏色繪制散點圖

[英]Plotting scatterplot with completely different colors

我正在嘗試創建一個散點圖,但是,我得到了不同類別的重復顏色(我有 10 個類別)。

from sklearn.decomposition import PCA
from sklearn.cluster import MiniBatchKMeans

pca = PCA(n_components=2, random_state=7)
reduced_features = pca.fit_transform(X_idf.toarray())
cls = MiniBatchKMeans(n_clusters=10, random_state=7)
cls.fit(X_idf)

pred = cls.predict(X_idf)
plt.scatter(reduced_features[:,0], reduced_features[:,1], c=pred, )
plt.scatter(reduced_cluster_centers[:, 0], reduced_cluster_centers[:,1], marker='x', s=200, 
c='b')
plt.title('K-means data distribution')

我曾嘗試在第一次 pl.scatter() 調用中添加一些顏色貼圖(例如:cmap='bwr'),但它並沒有解決我的問題。

我的 Y 數據 (c=pred) 是一個從 0 到 10 的列表。用於下圖的值 [...0 9 5 1 1 1 1 8 1 4 6 4 7 2 0 4 9 9 9 9 4 4 5 5 5 4 4 4 4 3 4 7 1 1 1 1 7 4 2 2 2 2 4 8 8 8 0 8 4 4 4 7 4 3 3 3 3 4 3 4 4 4 2 5 4 2 7 ...]

這是我目前的情節:

當前情節

有沒有人知道如何將 c 參數保留為預測類,但有不同的顏色可以讓我更好地對其進行可視化?

對於尋找具有 20 多個選項(又名“tab20”)的顏色圖的人來說,此方法工作正常:

def generate_colormap(number_of_distinct_colors=100):
    number_of_shades = 7
    number_of_distinct_colors_with_multiply_of_shades = int(math.ceil(number_of_distinct_colors / number_of_shades) * number_of_shades)
    linearly_distributed_nums = np.arange(number_of_distinct_colors_with_multiply_of_shades) / number_of_distinct_colors_with_multiply_of_shades
    arr_by_shade_rows = linearly_distributed_nums.reshape(number_of_shades, number_of_distinct_colors_with_multiply_of_shades // number_of_shades)

    # Transpose the above matrix (columns become rows) - as a result each row contains saw tooth with values slightly higher than row above
    arr_by_shade_columns = arr_by_shade_rows.T

    # Keep number of saw teeth for later
    number_of_partitions = arr_by_shade_columns.shape[0]
    nums_distributed_like_rising_saw = arr_by_shade_columns.reshape(-1)
    initial_cm = hsv(nums_distributed_like_rising_saw)

    lower_partitions_half = number_of_partitions // 2
    upper_partitions_half = number_of_partitions - lower_partitions_half
    lower_half = lower_partitions_half * number_of_shades
    for i in range(3):
        initial_cm[0:lower_half, i] *= np.arange(0.2, 1, 0.8/lower_half)

    # Modify second half in such way that colours towards end of partition are less intense and brighter
    # Colours closer to the middle are affected less, colours closer to the end are affected more
    for i in range(3):
        for j in range(upper_partitions_half):
            modifier = np.ones(number_of_shades) - initial_cm[lower_half + j * number_of_shades: lower_half + (j + 1) * number_of_shades, i]
            modifier = j * modifier / upper_partitions_half
            initial_cm[lower_half + j * number_of_shades: lower_half + (j + 1) * number_of_shades, i] += modifier

    return ListedColormap(initial_cm)

代碼不是我寫的,但我做了一些調整來改進它。 抱歉,我再也找不到原始參考鏈接了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM