How can I assign custom colors to stacked bar plot

1 次查看(过去 30 天)
Hi,
I am creating an image file to overlay later in google earth. The goal is to create an image in matlab that looks like a bar legend so I can add it to my map in google earth. I have done this by creating a stacked bar plot. I need 6 boxes for the legend which I have done, but my map uses specific colors so I can't use the color bars in matlab.
script for my plot: y = [1 1 1 1 1 1; 0 0 0 0 0 0;]; bar(y, 'stacked')
now I have my legend (bar plot) but I need to assign custom colors to each rectangle. I can assign one color to them all for example make them all red:
y = [1 1 1 1 1 1; 0 0 0 0 0 0;]; >> bar(y, 'stacked', 'r')
but I need 6 different custom colors. I have the RGB assigments for all 6 colors is there some way I can enter these into the script? then assign legend labels?
thanks!

回答(1 个)

Matt Tearle
Matt Tearle 2016-12-2
The colors of the bars are taken from the default colormap, so the easiest solution is to change the figure's colormap. Put the 6 RGB values into a matrix, then set the figure's colormap to that matrix:
>> c = rand(6,3)
c =
0.0462 0.0344 0.4898
0.0971 0.4387 0.4456
0.8235 0.3816 0.6463
0.6948 0.7655 0.7094
0.3171 0.7952 0.7547
0.9502 0.1869 0.2760
>> y = [1 1 1 1 1 1; 0 0 0 0 0 0];
>> b = bar(y, 'stacked');
>> b(1).Parent.Parent.Colormap = c;
  1 个评论
Tong Zhao
Tong Zhao 2018-5-20
Does not work for me... my code is the following: x=[a b c d;0 0 0 0]; ax1= bar(x,'stacked'); cmap = colormap([ 0 0 1; 0 1 0; 1 0 0;.5 .5 0]); ax1(1).Parent.Parent.Colormap = cmap;

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Colormaps 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by