2012-10-03 153 views
1

與三個數值一起,數據包含分類值(0或1),並希望使用三維散點圖顯示數據。我試圖寫一個函數來讀取CSV文件中的數據,並創建一個散點圖方式如下:在三維散點圖上顯示不同顏色的類別

function f = ScatterPlotUsers(filename) 

    data = ReadCSV(filename); 
    x = data(:,2); 
    y = data(:,3); 
    z = data(:,4); 

    size = ones(length(x), 1)*20; 
    userType = data(:,5); 
    colors = zeros(length(x), 1); 

    a = find(userType == 1); 
    b = find(userType == 0); 
    colors(a,1) = 42; %# color for users type a 
    colors(b,1) = 2; %# color for users type b 

    scatter3(x(:),y(:),z(:),size, colors,'filled') 
    view(-60,60); 

我其實想做的是爲一個顏色設置爲紅色和b爲藍色,但不管顏色值如何(例如42和2),點的顏色不會改變。 有誰知道什麼是正確的方式來確定幾個分類值(在這種情況下只有0和1)的特定顏色?

回答

2

你做得對,但是,你確定色圖條目42和2是指紅色和藍色?你可以嘗試明確給出RGB值:

colors = zeros(length(x), 3); 
colors(userType == 1, :) = [1 0 0]; %# colour for users type a (red) 
colors(userType == 2, :) = [0 0 1]; %# colour for users type b (blue) 

另外,我建議你改變變量size的名字,因爲size也是Matlab的命令; Matlab可能會對此感到困惑,並且您的代碼的任何未來讀者肯定會對此感到困惑。

2

我會用顏色表,特別是如果你userType值在0開始並增加:

% Read in x, y, z, and userType. 

userType = userType + 1; 

colormap(lines(max(userType))); 

scatter3(x, y, z, 20, userType); 

如果你想具體的顏色,用矩陣替代lines(...)。例如,如果你有3種用戶類型,你想讓他們的紅色,綠色和藍色:

colormap([1, 0, 0; 
      0, 1, 0; 
      0, 0, 1]); 

其他一些注意事項:

我們添加一個userType切換從0開始的索引,以1基於索引。

您可以對scatter3的size參數使用標量,而不是指定單個值的數組。

相關問題