簡體   English   中英

Matplotlib / Seaborn 散點圖不使用正確的標記和顏色條修復

[英]Matplotlib / Seaborn scatterplot dosen't use correct markers and colorbar fix

我正在嘗試可視化 UMAP 並且已經有以下代碼和 plot,我的目標是在我的數據集中為兩個類有兩個不同的標記,並且我的數據集中的每個組也有一個顏色(組是 VP XXX,請參見顏色欄在圖像中)實際上已經以某種方式解決了。 問題是標記不是我想要得到的標記,並且顏色條在告訴我哪個顏色是哪個組方面不是很准確。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

#### prepare lists ####
VP_with_col = []
m=[]
col = []
embedding = [[0,0.8],[0.5,0.5], [0.9,0.5],[0.2,0.9],[0.4,0.4],[0.6,0.5],[0.77,0.59],[0.8,0.1]]
EXAMPLE_VP = ["VP124","VP124","VP125", "VP125", "VP203", "VP203","VP258","VP258"]
EXAMPLE_LABELS = [0,1,0,1,0,1,0,1]
dataframe = pd.DataFrame({"VP": EXAMPLE_VP, "label": EXAMPLE_LABELS})
VP_list = dataframe.VP.unique()
# add color/value to each unique VP
for idx,vp in enumerate(VP_list): 
    VP_with_col.append([1+idx, vp]) #somehow this gives me a different color for each group which is great

#create color array of length len(dataframe.VP) with a color for each group
for idx, vp in enumerate(dataframe.VP):
    for vp_col in VP_with_col:
        if(vp_col[1] == vp):
         col.append(vp_col[0])   

#### create marker list ####
for elem in dataframe.label:
  if(elem == 0):
        m.append("o")
  else:
        m.append("^")

########################## relevant part for question ############################

#### create plot dataframe from lists and UMAP embedding ####
plot_df = pd.DataFrame(data={"x":embedding[:,0], "y": embedding[:,1], "color":col, "marker": m })

plt.style.use("seaborn")   
plt.figure()

#### Plot ####
ax= sns.scatterplot(data=plot_df, x="x",y="y",style= "marker" , c= col, cmap='Spectral', s=5 )
ax.set(xlabel = None, ylabel = None)
plt.gca().set_aspect('equal', 'datalim')

#### Colorbar ####
norm = plt.Normalize(min(col), max(col))
sm = plt.cm.ScalarMappable(cmap="Spectral", norm=norm)
sm.set_array([])

# Remove the legend(marker legend) , add colorbar
ax.get_legend().remove()
cb = ax.figure.colorbar(sm)  

cb.set_ticks(np.arange(len(VP_list)))
cb.set_ticklabels(VP_list)

##### save
plt.title('UMAP projection of feature space', fontsize=12) 
plt.savefig("./umap_plot",dpi=1200)

給我這個帶有標准標記和“x”標記的 plot。 style = "marker"中,dataframe 的標記列類似於["^", "o","^","^","^","o"...] 在此處輸入圖像描述

是否也可以在顏色欄中更清楚地說明哪種顏色屬於哪個class?

在沒有 Seaborn 的情況下,您正在執行 matplotlib 所需的大量操作。 使用 Seaborn,大部分是自動的。 以下是您的測試數據的樣子:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

embedding = np.array([[0, 0.8], [0.5, 0.5], [0.9, 0.5], [0.2, 0.9], [0.4, 0.4], [0.6, 0.5], [0.77, 0.59], [0.8, 0.1]])
EXAMPLE_VP = ["VP124", "VP124", "VP125", "VP125", "VP203", "VP203", "VP258", "VP258"]
EXAMPLE_LABELS = [0, 1, 0, 1, 0, 1, 0, 1]
plot_df = pd.DataFrame({"x": embedding[:, 0], "y": embedding[:, 1], "VP": EXAMPLE_VP, "label": EXAMPLE_LABELS})

plt.figure()
plt.style.use("seaborn")

ax = sns.scatterplot(data=plot_df, x="x", y="y",
                     hue='VP', palette='Spectral',
                     style="label", markers=['^', 'o'], s=100)
ax.set(xlabel=None, ylabel=None)
ax.set_aspect('equal', 'datalim')
# sns.move_legend(ax, bbox_to_anchor=(1.01, 1.01), loc='upper left')

plt.tight_layout()
plt.show()

帶有顏色和標記的 seaborn 散點圖

請注意, 'Spectral'顏色圖將淺黃色分配給“VP203”,這在默認背景下很難看到。 您可能希望對 colors 使用例如palette='Set2'

暫無
暫無

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

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