Search code examples
matlabplotcolorsmatlab-figure

Bar plot switch colors in Matlab


I have the following code in Matlab, which produces a useful plot for me. Now I'd like to make the plot comparable color wise with another plot. For this reason, some colors should be switched: colors for...

'Pre split total EON' with 'Post split total EON'

'Pre split pure EON' with 'Post split pure EON'

'Pre split total RWE' with 'Post split total RWE'

'Pre split pure RWE' with 'Post split pure RWE'.

That is all, but I do not know how to do it, since the colors are assigned automatically...

clear all
close all

values = [4 1 11 2 3; 4 1 5 2 -10];
names = {'Pre split total EON' 'Post split total EON'...
    'Pre split pure EON' 'Post split pure EON' 'Post split Uniper';...
    'Pre split total RWE' 'Post split total RWE'...
    'Pre split pure RWE' 'Post split pure RWE' 'PostSplitInnogy'};
categories = {'EON','RWE'};
figure;
b = bar(values,'FaceColor','flat');
ticksList = b(1).XData+arrayfun(@(x)x.XOffset, b)';
xticks(ticksList(:))
xticklabels([names(1,:)';names(2,:)'])
xtickangle(90)
ax1 = gca;
ax2 = axes('Position', get(ax1, 'Position'),'Color', 'none');
set(ax2, 'XAxisLocation', 'top','YAxisLocation','Right');
set(ax2, 'XLim', get(ax1, 'XLim'),'YLim', get(ax1, 'YLim'));
set(ax2, 'YTick', []);
xticks(b(1).XData)
xticklabels(categories)
for k = 1:size(values,2) % for fancier colors.
    b(k).CData = k;
end

enter image description here


Solution

  • I feel like you assigned the colors manually in:

    for k = 1:size(values,2) % for fancier colors.
        b(k).CData = k;
    end
    

    if you just want to change the order you can do so by

    b(1).Cdata = 2;
    

    and so on. Alternativly you can change all in one with

    [b.CData] = deal(2,1,4,3,5);