Plot a matrix, values as colors

前端 未结 2 828
长情又很酷
长情又很酷 2021-01-07 10:50

I have random matrix with arbitrary dimensions and I want to assign a color for each value (randomly or not) and plot the matrix with numbers like,

相关标签:
2条回答
  • 2021-01-07 11:20

    Using imagesc instead of pcolor solves the problem. It also brings some other benefits:

    • Avoids the need for flipud;
    • The coordinates of the text objects become integer values;
    • Axes are automatically set to "matrix" mode, with the origin in the upper right corner.

    Code:

    m = 8;
    n = 6;
    A = randi(5,[m n]);
    imagesc(A);
    for ii = 1:n
        for jj = 1:m
            text(ii, jj, num2str(A(jj,ii)), 'FontSize', 18);
        end
    end
    

    For

    A =
         4     5     4     2     4     4
         5     4     3     4     4     2
         5     4     1     1     1     3
         4     3     5     2     5     4
         1     2     2     2     5     3
         1     5     2     5     1     3
         4     3     1     3     3     1
         3     1     2     4     2     3
    

    this produces

    enter image description here

    0 讨论(0)
  • 2021-01-07 11:23

    I just padded the matrix prior to pcolor and I think it's the effect you wanted. The reason it works comes from the help doc for pcolor, which states that

    In the default shading mode, 'faceted', each cell has a constant color and the last row and column of C are not used.

    m = 12;
    n = 8;
    A = randi(5,[m n]);
    Arot = flipud(A);
    Arot = [ Arot; Arot(end,:) ];
    Arot = [ Arot, Arot(:,end) ];
    pcolor(Arot);figure(gcf);
    for i = 1 : n
      for j = 1 : m
        text(i + .5 , j + .5 ,num2str(Arot(j,i)),'FontSize',18);
      end
    end
    
    0 讨论(0)
提交回复
热议问题