Наличие групп одного цвета на столбчатой ​​диаграмме и наличие элементов легенды на столбцах - PullRequest
0 голосов
/ 05 января 2019

У меня есть гистограмма, как показано ниже, а x - матрица 8x3. Мои коды как

x=[0.2193   0.2281  0;
0.193   0.1404  0;
0.2045  0.1875  0.159;
0.0625  0.0568  0;
0.1993  0.1554  0.1318;
0.0878  0.0034  0;
0.1369  0.1103  0.1027;
0.0951  0.076   0];

x0=10;
y0=10;
width=1200;
height=500;
set(gcf,'position',[x0,y0,width,height])

a=bar(x,'BarWidth',0.9);
a(1).FaceColor=[0.9290, 0.6940, 0.1250];
a(2).FaceColor=[0, 0.4470, 0.7410];
a(3).FaceColor=[0.4660, 0.6740, 0.1880];


lgd=legend('Method 1','Method 2','Method 3');
title('False Negative Rates')
xlabel('Clusters')
ylabel('False Negative Rate')
xticklabels({'Cl1 - PRed','Cl1 - PYellow','Cl2 - PRed','Cl2 - PYellow', 'Cl3 - PRed','Cl3 - PYellow', 'Cl4 - PRed','Cl4 - PYellow'})
saveas(gcf,'False Negatives.png')

Как видите, на графике 8 групп. enter image description here Мне нужно сделать три вещи с этим графиком:

  1. 1-я, 3-я, 5-я и 7-я группы должны быть красного цвета, а остальные - желтого.
  2. Мне нужно написать элементы легенды внутри каждого бара. Если он не помещается внутри, то над ним вертикально. У красных полос будет белый шрифт, у желтых - черный.
  3. Если значение равно 0, показать его линией на горизонтальной оси.

Я прошел через это, но не мог применить аналогично. Как сделать так, чтобы группы горизонтальных полос были одного цвета?

Как мне достичь чего-либо или всего этого?

1 Ответ

0 голосов
/ 05 января 2019

Вам нужно следовать следующему алгоритму, чтобы правильно получить график в соответствии с требованиями.

  1. Цикл для каждого элемента отдельно в матрице х.
  2. И для каждого элемента нанесите соответствующую гистограмму и удерживайте.
  3. Проверьте номер каждого столбца в распределительном шкафу и, соответственно, поставьте легенды вертикально над столбцами.
  4. Далее, проверьте, является ли номер строки нечетным, если да, то измените цвет полосы на красный и цвет легенды на белый. На этом этапе фиксируйте положение легенд внутри / снаружи стержней в зависимости от длины стержня.
  5. Если строка является четным числом, измените цвет полосы на желтый, измените цвет легенды на черный и исправьте положение легенды соответственно длине полосы.
  6. Наконец, проверьте, равна ли длина полосы x 0, если да, увеличьте ширину линии и сдвиньте легенду полосы вверх.
  7. Увеличьте переменную зазора бара и закройте внутренний цикл.
  8. Снова увеличить переменную зазора бара и закрыть внешнюю петлю.
  9. Отложить и поставить заголовок, галочки и метки.

Код для выполнения приведен ниже.

clc
close all

% declare the points, for the bars
x=[0.2193   0.2281  0;
0.193   0.1404  0;
0.2045  0.1875  0.159;
0.0625  0.0568  0;
0.1993  0.1554  0.1318;
0.0878  0.0034  0;
0.1369  0.1103  0.1027;
0.0951  0.076   0];

% declare the figure width and height
x0=10;
y0=10;
width=1200;
height=500;
% create the figure
set(gcf,'position',[x0,y0,width,height]);
% get the number of rows and column in x points
[row, col] = size(x);
% variable to decide the gap between the bars
p = 1;

%%%%%%  Loop for Rows %%%%%%%%
for r = 1:row

    %%%%%%%%%% loop for each elements in each row %%%%%%%
    % loop for columns %
    for c = 1:col
        % draw the individual bar
        a = bar(p, x(r,c), 'BarWidth',0.9); hold on
        % switch the column value
        switch(c)
            % if column is 1 then create bar legend as "Method 1"
            % vertically just above the bar
            case 1 
                t1 = text(p,x(r,c),'Method 1','rotation',90);
            % if column is 2 then create bar legend as "Method 2"
            % vertically just above the bar
            case 2
                t1 = text(p,x(r,c),'Method 2','rotation',90);
            % if column is 3 then create bar legend as "Method 3"
            % vertically just above the bar
            case 3
                t1 = text(p,x(r,c),'Method 3','rotation',90);
        end

        % Now check whether the row is odd
        % if yes then change the bar color to Red
        if(rem(r, 2) ~= 0)
            set(a, 'FaceColor', 'r')
            % Change the legend color to white in red bars
            t1.Color = 'White';
            % check if x value is equals or greaten than 
            % 0.05, it means the legend fit inside the bars
            if(x(r,c) >= 0.05)
                % slide down the legend into the bars
                t1.Position = [p, x(r,c)-0.04];
            else
                % else change the color of the 
                % legend to black and keep the
                % position unchanged, because if the 
                % position remains outside the red bars
                % then the legend would not be visible due 
                % to the color white and hence change it to black
                t1.Color = 'black';
            end
        else
           % else, it means row is even then
           % change the bar color to yellow
           set(a, 'FaceColor', 'y')
           % if bar color is yellow then change the legend
           % color to black
            t1.Color = 'black';
            % check if length of bar is greater than 0.05
            % if yes slide the legend position inside the bar
              if(x(r,c) >= 0.05)
                t1.Position = [p, x(r,c)-0.04];
              end
        end

        % finally, check if x is equal to 0
        % then make the line width of bar to
        % 2 points, to make it more visible
        % and slide up the legend above the bar
        % to few fractional points to make it more ligible
        if(x(r,c) == 0)
            a.LineWidth = 2;
            t1.Position = [p, x(r,c)+0.002];
        end

        % increment the legend gap as y-axis
        p = p+1;

    end
    %%%%% END the Column loop %%%%%%%%%

    % on each row end increment the gap of bars to
    % make it categorized as each row.
    p = p+1;
end
%%%%%%%%% END the Row loop %%%%%%%%%%%

hold off
% set the title
title('False Negative Rates')
% set the labels
xlabel('Clusters')
ylabel('False Negative Rate')
% mark the xticks to put the xticklables
% in next line
xticks([2:4:32])
% change the xtick labels at corresponding xticks
xticklabels({'Cl1 - PRed','Cl1 - PYellow','Cl2 - PRed','Cl2 - PYellow', 'Cl3 - PRed','Cl3 - PYellow', 'Cl4 - PRed','Cl4 - PYellow'})
saveas(gcf,'False Negatives.png')

OUTPUT

enter image description here

...