2016-11-09 204 views
2

我有一個矩陣單元,我想繪製所有點到3個圖(x,y1)(x,y2)(x,y3)Matlab繪圖二維散點和線組

   y1  y2  y3  x 
BCLK103  4.000 5.102 7.055 10 
BCLK103  4.100 5.112 7.555 5 
BCLK103  4.600 6.182 9.55  3 
BCLK105  5.000 5.112 7.255 11 
BCLK105  4.060 6.12  8.555 6 
BCLK109  4.050 5.112 7.152 10 
BCLK109  7.000 5.112 7.545 5 
BCLK109  4.900 6.142 8.545 2 
BCLK110  3.900 6.311 8.100 2 

我想繪製組中的線路在每個圖,在圖y1線eg.a爲BCLK103連接三個點(4.000, 4.100, 4.600),在y2圖的BCLK103線應該連接三個點(5.102, 5.112, 6.182),一條線爲在y3圖中應該連接三個點(7.055, 7.555, 9.55); BCLK105的一條線在y1圖中連接了兩個點(5.000, 4.060)等。BCLK110只有一個點,因此它不能在每個圖中形成一條線。但是我仍然希望將它的點繪製在每個圖表中。

我嘗試這樣做:

figure; 
f1 = plotmatrix(x,y1); 
hold on 

for n = 1:9 

    sameGroup = strcmp(allData(n+1,1), allData(n,1)); 

    if sameGroup 

     tempx1 = cell2mat(allData(n,5)); 
     tempx2 = cell2mat(allData(n+1,5)); 
     tempy1 = cell2mat(allData(n,2)); 
     tempy2 = cell2mat(allData(n+1,2)); 

     tempx = [tempx2, tempx1]; 
     tempy = [tempy2, tempy1]; 

     plot(tempx, tempy, '-'); 

    end 
end 

hold off 

但僅MATLAB繪製,沒有任何線散點圖。請人教我如何繪製點?我正確使用hold on嗎?

回答

1

的問題是,你在循環中僅提取單點:

tempx1 = cell2mat(allData(n,5)); 
% 'n' is the loop index, and thus scalar. therefore, 
% tempx1 is a scalar. Similar for the rest. 

plot()需求向量/矩陣輸入,能夠知道哪些點連接到其他點。下面是我會怎麼做:

function plot_example() 

    % Your data (probably passed via function argument) 
    allData = {... 
     NaN  'y1'  'y2'  'y3'  'x' 
     'BCLK103' 4.000 5.102 7.055 10 
     'BCLK103' 4.100 5.112 7.555 5 
     'BCLK103' 4.600 6.182 9.55  3 
     'BCLK105' 5.000 5.112 7.255 11 
     'BCLK105' 4.060 6.12  8.555 6 
     'BCLK109' 4.050 5.112 7.152 10 
     'BCLK109' 7.000 5.112 7.545 5 
     'BCLK109' 4.900 6.142 8.545 2 
     'BCLK110' 3.900 6.311 8.100 2 
    }; 

    % Rename for convenience (might need to be generalized) 
    gp = allData(2:end, 1); 
    y1 = [allData{2:end, 2}]; 
    y2 = [allData{2:end, 3}]; 
    y3 = [allData{2:end, 4}]; 
    x = [allData{2:end, 5}]; 

    % Unique group IDs 
    gu = unique(gp); 

    % Plot all desired plots in a single figure 
    figure('position', [400, 200, 1200, 600]); 

    do_plot(1, y1); 
    do_plot(2, y2); 
    do_plot(3, y3); 

    % Helper function doing the actual work 
    function do_plot(pltind, ydata) 

     subplot(1,3, pltind); 
     hold on 
     plot(x, ydata, '.'); 

     legendentries = ['scatter'; gu]; 
     for ii = 1:numel(gu) 

      % Make slice according to group ID 
      gp_inds = strcmp(gu{ii}, gp); 

      % Pick a Unique color, taking into account that 
      % that only may be one point 
      colcmd = {'color', rand(1,3)}; 
      if sum(gp_inds) == 1 
       colcmd = ['x' colcmd 'markersize' 10]; end %#ok<AGROW> 

      % Use plot(), is a line plotter by default 
      plot(x(gp_inds), ydata(gp_inds), colcmd{:}); 

     end 

     xlabel('x') 
     ylabel(['y' int2str(pltind)]) 
     legend(legendentries) 

    end 

end 

結果:

result from running the function above