Drawing bar graph with different colors in Matlab 2013a

1 view (last 30 days)
I am working with Matlab 2013a and I want to make a bar graph of a vector like v2=[2.4 9 18]
I want each bar will have different color
I have tried the following code, but it does not work:
v2 = [2.4 9 18];
handle = bar(v2);
barColorMap = jet(3);
for k = 1:3
set(handle(k), 'FaceColor', barColorMap(k, :));
end
but it does not work. I appreciate if someone can help me on this.

Answers (1)

ag
ag on 6 May 2025
Hi Shirin,
To define the color for a "Bar" individually, you can use the bar property "CData". You will first need to set the "FaceColor" property of the bar object to "flat" so that the chart uses the colors defined in the "CData" property.
The below code demonstrates how to achieve the same:
v2 = [2.4 9 18];
handle = bar(v2);
barColorMap = jet(3);
handle.FaceColor = 'flat';
handle.CData = barColorMap;
Hope this helps!

Categories

Find more on Color and Styling in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!