Matlab 如何更改条形图中条形的颜色?

Matlab 如何更改条形图中条形的颜色?,matlab,plot,graph,colors,histogram,Matlab,Plot,Graph,Colors,Histogram,我想创建一个条形图,在其中更改一些条形图的颜色。 我的条形图的代码如下所示: 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) 我希望前六条为黑色,后六条为蓝色,但我不知道怎么做。

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

 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)

我希望前六条为黑色,后六条为蓝色,但我不知道怎么做。

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


以下内容改编自MATLAB Central:

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
y=[0.04552309、-0.001730885、0.023943445、0.065564478、0.032253892、0.013442562、-0.01172323、0.024595622、-0.100614203、-0.001444697、0.019383706、0.890249809];
对于ii=1:12
h=巴(ii-0.5,y(ii));
如果ii==1
等等
结束

如果ii无需单独绘制,以下是简单的解决方案:

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') 

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

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

bar(x,diag(y),'stacked'); % x will be usually defined as x = 1:number_of_bars
colormap(mycolors);
就这些。神奇之处在于diag函数和“堆叠”标记,使matlab认为您有更多的数据(但它们都是0)。

正如答案所示,由于版本为matlab R2017b,您可以通过CData属性来实现。您可以在文档页面找到更多信息

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

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];

事实上,路易斯的回答更简单、更有效。谢谢你的回答!也许你可以回答关于这个条形图的另一个问题:)。我该怎么做才能得到条顶上y的不同值?我想我需要这样的东西:对于i1=1:numel(y)text(x(i1),y(i1),num2str(y(i1),“%0.2f”),…“水平对齐”,“中心”,“垂直对齐”,“底部”)end,但我没有x:(.您知道如何修复它吗?提前谢谢您!@user2971574您案例中的x位置只是i索引。因此,将
x(i1)
替换为
i1
,即:
对于i1=1:numel(y)、text(i1,y(i1)、num2str(y(i1),'%0.2f')、'HorizontalAlignment'、'center'、'VerticalAlignment'、'bottom')、end
另请参见:
bar(x,diag(y),'stacked'); % x will be usually defined as x = 1:number_of_bars
colormap(mycolors);
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];