【问题标题】:How can I change the color of bars in bar graph?如何更改条形图中条形的颜色?
【发布时间】:2013-12-11 23:36:48
【问题描述】:

我想创建一个条形图,在其中更改一些条形的颜色。 我的条形图代码如下:

 y = [0.04552309, -0.001730885, 0.023943445, 0.065564478, 0.032253892, 0.013442562, ...
      -0.011172323, 0.024595622, -0.100614203, -0.001444697, 0.019383706, 0.890249809];
 bar(y)

我希望前 6 个条为黑色,最后 6 个条为蓝色,但我不知道该怎么做。

【问题讨论】:

标签: matlab plot graph colors histogram


【解决方案1】:

您需要分别绘制它们(但在相同的轴上):

bar(1:6,y(1:6),'k')
hold on
bar(7:numel(y),y(7:end),'b')
set(gca,'xtick',1:numel(y))

【讨论】:

  • 也许您可以回答有关此条形图的另一个问题 :)。我该怎么做才能在条形顶部获得不同的 y 值?我想我需要这样的东西:
  • for i1=1:numel(y) text(x(i1),y(i1),num2str(y(i1),'%0.2f'),... 'Horizo​​ntalAlignment', 'center',... 'VerticalAlignment','bottom') 结束
  • 但是我没有 x :(。你知道怎么解决吗?提前谢谢你!
  • @user2971574 在您的情况下,x 位置只是 i 索引。所以将x(i1)替换为i1,即:for i1=1:numel(y), text(i1,y(i1),num2str(y(i1),'%0.2f'),'HorizontalAlignment','center','VerticalAlignment','bottom'), end
【解决方案2】:

正如HERE 的回答所暗示的那样,从 MATLAB R2017b 版本开始,您可以通过 CData 属性执行此操作。您可以在 THIS 文档页面找到更多信息。

简单地说,使用以下方法将得到你所需要的。

b = bar(rand(10,1));
b.FaceColor = 'flat';
% Change the color of the second bar. Value assigned defines RGB color value.
b.CData(2,:) = [.5 0 .5];

【讨论】:

    【解决方案3】:

    以下内容改编自 MATLAB Central 上的Bar plot with bars in different colors

    y= [0.04552309, -0.001730885, 0.023943445, 0.065564478, 0.032253892, 0.013442562,    -0.011172323, 0.024595622, -0.100614203, -0.001444697, 0.019383706, 0.890249809];
    for ii=1:12
      h = bar(ii-0.5, y(ii));
      if ii == 1
         hold on
      end
      if ii<=6
         col = 'k';
      else
         col = 'b';
      end    
      set(h, 'FaceColor', col,'BarWidth',0.4) 
    end
    axis([0 12 -0.2 1])
    hold off
    

    【讨论】:

    • 其实 Luis 的回答要简单得多,也有效得多。
    【解决方案4】:

    不需要单独绘制,这里是简单的解决方案:

    y= [0.04552309, -0.001730885, 0.023943445, 0.065564478, 0.032253892, 0.013442562,    -0.011172323, 0.024595622, -0.100614203, -0.001444697, 0.019383706, 0.890249809];
    figure,
    bar(y)
    
    y1 = zeros(1,length(y));
    y1(3:5) = y(3:5);
    hold on
    h = bar(y1)
    set(h, 'FaceColor', 'k') 
    

    See output

    【讨论】:

      【解决方案5】:

      像往常一样很晚,但有一种简单的方法可以“欺骗”matlab。 您首先定义您的颜色图(例如 3 种不同的颜色):

      mycolors = lines(3) % or just specify each row by hand
      

      然后您按以下方式绘制条形图:

      bar(x,diag(y),'stacked'); % x will be usually defined as x = 1:number_of_bars
      colormap(mycolors);
      

      就是这样。魔术来自 diag 函数和 'stacked' 标签,这使得 matlab 认为你有更多的数据(但它们都是 0)。

      【讨论】:

        猜你喜欢
        • 2011-08-03
        • 2012-01-19
        • 1970-01-01
        • 2016-05-18
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 2018-10-28
        相关资源
        最近更新 更多