Как отобразить массив с текстовым полем на рисунке? - PullRequest
3 голосов
/ 18 апреля 2019

Я пытаюсь отобразить массив в виде фигуры в MATLAB, используя цветное текстовое поле, которое изменяется в зависимости от значения в этом месте.

До сих пор я пытался использовать инструмент редактирования графиков MATLAB, чтобы нарисовать такую ​​фигуру, а затем сгенерировать код, чтобы увидеть, как он может выглядеть. Вот что я придумал:

figure1=figure

annotation(figure1,'textbox',...
    [0.232125037302298 0.774079320113315 0.034810205908684 0.0410764872521246],...
    'String','HIT',...
    'FitBoxToText','off',...
    'BackgroundColor',[0.470588235294118 0.670588235294118 0.188235294117647]);

annotation(figure1,'textbox',...
    [0.27658937630558 0.774079320113315 0.034810205908684 0.0410764872521246],...
    'String',{'STAY'},...
    'FitBoxToText','off',...
    'BackgroundColor',[1 0 0]);

Здесь результат выглядит не очень хорошо. Я хотел бы что-то аккуратное и не так сложно написать. Визуально я бы хотел что-то вроде этого:

enter image description here

Ответы [ 2 ]

2 голосов
/ 19 апреля 2019

Я нашел возможное решение с помощью функции pcolor .

Предупреждение: я тестировал только с октавой

Если вы хотите создать (m x n) таблицу с 4 цветами, как вам нужно, вы должны:

  • создать массив размером (m+1 x n+1) из диапазона integers' in the 1: 4`, установив их в соответствии с желаемым порядком
  • Позвоните pcolor, чтобы построить стол
  • настроить размер figure
  • создайте свой colormap в соответствии с желаемыми цветами
  • установить карту цветов
  • добавить нужный текст, используя текстовую функцию
  • установить tick и ticklabel осей

Изменить, чтобы ответить на комментарий

В дальнейшем вы можете найти возможную реализацию предложенного решения.

Код создает два figure:

  • В первом из них будут отображены значения входной матрицы
  • Во втором пользовательские строки

Ассоциация "значение цвета" выполняется через пользовательскую цветовую карту.

Поскольку в матрице x есть 4 различных возможных значения (это было определено как x=randi([1 4],n_row+1,n_col+1);), цветовая карта должна состоять из записи 4 RGB следующим образом.

cm=[1 0.3 0.3   % RED
    0.3 0.3 1   % BLUE
    0   1   0   % GREEN
    1   1   1]; % WHITE

Если вы хотите изменить ассоциацию, вам просто нужно изменить порядок строк цветовой карты.

Комментарии в коде должны прояснить вышеупомянутые шаги.

Код обновлен

% Define a rnadom data set
n_row=24;
n_col=10;
x=randi([1 4],n_row+1,n_col+1);

for fig_idx=1:2
   % Open two FIGURE
   % In the first one wil be ploted the values of the input matrix
   % In the second one the user defined strings
   figure('position',[ 1057    210    606    686])
   % Plot the matrix
   s=pcolor(x);
   set(s,'edgecolor','w','linewidth',3)
   % Define the colormap

   %cm=[1 1 1
   %    0 1 0
   %    0.3 0.3 1
   %    1 0.3 0.3];


   cm=[1 0.3 0.3   % RED
       0.3 0.3 1   % BLUE
       0   1   0   % GREEN
       1   1   1]; % WHITE

   % Set the colormap
   colormap(cm);
   % Write the text according to the color
   [r,c]=find(x(1:end-1,1:end-1) == 1);
   for i=1:length(r)
      if(fig_idx == 1)
         ht=text(c(i)+.1,r(i)+.5,num2str(x(r(i),c(i))));
      else
         ht=text(c(i)+.1,r(i)+.5,'SUR');
      end
      set(ht,'fontweight','bold','fontsize',10);
   end
   % Write the text according to the color
   [r,c]=find(x(1:end-1,1:end-1) == 2);
   for i=1:length(r)
      if(fig_idx == 1)
         ht=text(c(i)+.1,r(i)+.5,num2str(x(r(i),c(i))));
      else
         ht=text(c(i)+.1,r(i)+.5,'DBL');
      end
      set(ht,'fontweight','bold','fontsize',10);
   end
   % Write the text according to the color
   [r,c]=find(x(1:end-1,1:end-1) == 3);
   for i=1:length(r)
      if(fig_idx == 1)
         ht=text(c(i)+.1,r(i)+.5,num2str(x(r(i),c(i))));
      else
         ht=text(c(i)+.1,r(i)+.5,'HIT');
      end
      set(ht,'fontweight','bold','fontsize',10);
   end
   % Write the text according to the color
   [r,c]=find(x(1:end-1,1:end-1) == 4);
   for i=1:length(r)
      if(fig_idx == 1)
         ht=text(c(i)+.1,r(i)+.5,num2str(x(r(i),c(i))));
      else
         ht=text(c(i)+.1,r(i)+.5,'STK');
      end
      set(ht,'fontweight','bold','fontsize',10);
   end
   % Create and set the X labels
   xt=.5:10.5;
   xtl={' ';'2';'3';'4';'5';'6';'7';'8';'9';'10';'A'};
   set(gca,'xtick',xt);
   set(gca,'xticklabel',xtl,'xaxislocation','top','fontweight','bold');
   % Create and set the X labels
   yt=.5:24.5;
   ytl={' ';'Soft20';'Soft19';'Soft18';'Soft17';'Soft16';'Soft15';'Soft14';'Soft13'; ...
        '20';'19';'18';'17';'16';'15';'14';'13';'12';'11';'10';'9';'8';'7';'6';'5'};
   set(gca,'ytick',yt);
   set(gca,'yticklabel',ytl,'fontweight','bold');
   title('Dealer''s Card')
end

Таблица со значениями во входной матрице

enter image description here

Таблица с пользовательскими строками

enter image description here

1 голос
/ 19 апреля 2019

Это ответ, вдохновленный ответом il_raffa , но также с некоторыми отличиями. Нет лучше или хуже, это просто вопрос предпочтений.

Основные отличия:

  • используется imagesc вместо pcolor
  • он использует второй наложенный axes для точного управления сеткой color/thickness/transparency и т. Д. *
  • Связь между value - label - color устанавливается в самом начале в одной таблице. Весь код будет уважать это таблица.

Это выглядит так:

%% Random data
n_row = 24;
n_col = 10;
vals = randi([1 4], n_row, n_col);

%% Define labels and associated colors
% this is your different labels and the color associated. There will be
% associated to the values 1,2,3, etc ... in the order they appear in this
% table:
Categories = {
    'SUR' , [1 0 0] % red       <= Label and color associated to value 1
    'DBL' , [0 0 1] % blue      <= Label and color associated to value 2
    'HIT' , [0 1 0] % green     <= Label and color associated to value 3
    'STK' , [1 1 1] % white     <= you know what this is by now ;-)
    } ;

% a few more settings
BgColor  = 'w' ; % Background color for various elements
strTitle = 'Dealer''s Card' ;

%% Parse settings
% get labels according to the "Categories" defined above
labels = Categories(:,1) ;
% build the colormap according to the "Categories" defined above
cmap = cell2mat( Categories(:,2) ) ;

%% Display
hfig = figure('Name',strTitle,'Color',BgColor,...
              'Toolbar','none','Menubar','none','NumberTitle','off') ;
ax1 = axes ;

imagesc(vals)     % Display each cell with an associated color
colormap(cmap);   % Set the colormap
grid(ax1,'off')   % Make sure there is no grid 

% Build and place the texts objects
textStrings = labels(vals) ;
[xl,yl]     = meshgrid(1:n_col,1:n_row);
hStrings    = text( xl(:), yl(:), textStrings(:), 'HorizontalAlignment','center');

%% Modify text color if needed
% (White text for the darker box colors)
textColors = repmat(vals(:) <= 2 ,1,3);
set(hStrings,{'Color'},num2cell(textColors,2));

%% Set the axis labels
xlabels = [ cellstr(num2str((2:10).')) ; {'A'} ] ;
ylabels = [ cellstr(num2str((5:20).')) ; cellstr(reshape(sprintf('soft %2d',[13:20]),7,[]).') ] ;

set(ax1,'XTick',        1:numel(xlabels), ...
        'XTickLabel',   xlabels, ...
        'YTick',        1:numel(ylabels), ...
        'YTickLabel',   ylabels, ... 
        'TickLength',   [0 0], ...
        'fontweight',   'bold' ,...
        'xaxislocation','top') ;

title(strTitle)

%% Prettify
ax2 = axes ; % create new axe and retrieve handle
% superpose the new axe on top, at the same position
set(ax2,'Position', get(ax1,'Position') );
% make it transparent (no color)
set(ax2,'Color','none')
% set the X and Y grid ticks and properties
set(ax2,'XLim',ax1.XLim , 'XTick',[0 ax1.XTick+0.5],'XTickLabel','' ,... 
        'YLim',ax1.YLim , 'YTick',[0 ax1.YTick+0.5],'YTickLabel','' ,...
        'GridColor',BgColor,'GridAlpha',1,'Linewidth',2,...
        'XColor',BgColor,'YColor',BgColor) ;
% Make sure the overlaid axes follow the underlying one
resizeAxe2 = @(s,e) set(ax2,'Position', get(ax1,'Position') );
hfig.SizeChangedFcn = resizeAxe2 ;

Получает следующий рисунок: enter image description here

Конечно, вы можете заменить цвета вашими любимыми цветами. Я бы посоветовал вам поиграть с настройками сетки ax2 для различных эффектов, а также вы можете поиграть со свойствами объектов text (выделите их жирным шрифтом, другим цветом и т. Д.). Веселитесь!

...