How to change bars colour in MATLAB

后端 未结 3 394
生来不讨喜
生来不讨喜 2021-01-25 20:27

I am new to programming so I am learning introductory to MATLAB I was wondering how you could change colours of bar in MATLAB.

this is my script. Can someone please help

相关标签:
3条回答
  • 2021-01-25 20:39

    bar can take third argument, which is color value, e.g. bar(x,y, 'r').

    0 讨论(0)
  • 2021-01-25 20:48

    Whilst this is overkill for your specific question, in general, to change the colour of bars depending on their height, you can apply a colormap to the bars. This is mainly from the bar documentation.

    x = 1:8;
    y = 10*x;
    h=bar(y);  %// create a sample bar graph
    

    For the colormap MAP, you do this:

    colormap(MAP)
    ch = get(h,'Children');
    fvd = get(ch,'Faces');
    fvcd = get(ch,'FaceVertexCData');
    [zs, izs] = sort(y);
    for i = 1:length(x)
        row = izs(i);
        fvcd(fvd(row,:)) = i;
    end
    set(ch,'FaceVertexCData',fvcd)
    hold off
    

    And, for example, using the builtin colormap hsv, you get enter image description here

    But in this case we want a very specific colormap,

    b=40 %// the cut-off for changing the colour
    MAP=zeros(length(x),3); %// intialise colormap matrix
    MAP(y<b,:)=repmat([0 0 1],sum(y<b),1); %// [0 0 1] is blue, when y<40
    MAP(y>=b,:)=repmat([0 1 0],sum(y>=b),1); %// [0 1 0] is green, for y>=40
    colormap(MAP)
    

    which gives

    enter image description here

    0 讨论(0)
  • 2021-01-25 21:00

    To use two different colors depending on y: compute a logical index depending on y values and call bar twice with appropriate arguments:

    x = [1:8];
    y = [20 30 40 50 60 70 80];
    ind = y < 40; %// logical index
    bar(x(ind), y(ind), 'facecolor', 'b', 'edgecolor', 'k') %// blue bars, black edge
    hold on %// keep plot
    bar(x(~ind), y(~ind), 'facecolor', 'g', 'edgecolor', 'k') %// green bars, black edge
    set(gca,'xtick',x)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题