color individual bar with different colors in bar plot

785 Ansichten (letzte 30 Tage)
shaz
shaz am 1 Jan. 2013
Kommentiert: Frederik am 20 Mär. 2024 um 3:22
a=[1 ;2; 3; 4]; b=[5 ;6 ;7 ;8];
bar(a,b)
how can i define different colors for individual bars
thanks in advance

Antworten (5)

Randi Cabezas
Randi Cabezas am 11 Jul. 2013
Here is a simple work around:
suppose you have a and b as in your question. then doing
h = bar(a,diag(b),'stacked');
will produce a different color for each bar. If you want to set your own colors then simply do:
set(h(<insert bar index here>),'facecolor',<insert your color here>).
Long explanation
This is tricking matlab into thinking there are multiple plotting elements (since the second input is a matrix). The documentation states that 'bar' will draw a bar for each column . It just so happens that all but one element of the columns are set to zero, yielding bars that are not visible. The option 'stacked' is used to avoid extra spacing (try 'group and you'll see the empty space).
the original colors
the original colors of the bar are obtained from the current figure's colormap. That is, the bar colors are something like
figColorMap = get(gcf,'colormap')
colorIndex = linespace(1,length(figColorMap),length(b));
barColor = figColorMap(colorIndex,:);
Hope it helps.

Timon Schulz
Timon Schulz am 19 Jul. 2020
If someone is looking for an easy solution the documentation states under 'CData' - Color Data:
b = bar(x,y,'FaceColor','flat')
b.CData(2,:) = [1 0 0];
This will make your second bar red.
If you want your third bar blue it'll be:
b = bar(x,y,'FaceColor','flat')
b.CData(3,:) = [0 0 1];
  4 Kommentare
Chaymae
Chaymae am 26 Jan. 2024
Thank you this has been soo helpful
Frederik
Frederik am 20 Mär. 2024 um 3:22
Does not work

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 1 Jan. 2013
Bearbeitet: Image Analyst am 1 Jan. 2013
Each bar series can have only one color, so you have to plot multiple bar plots on the same plot - just one single bar for each call to bar().
Then set the color of each barseries with the 'FaceColor' property:
% Demo macro plot 4 bars and give a different color to each one.
% Also plots the value of the bar above the bar.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 30;
format compact
% Ask user for the number of bars.
defaultValue = 4;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the number of bars';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', integerValue);
uiwait(warndlg(message));
end
% Define sample data in the range 20-80.
x = 1 : integerValue;
y = 20 + 80 * rand(integerValue)
numberOfBars = length(y);
button = menu('Use which colormap?', 'Custom', 'Random', 'Jet', 'Hot', 'Lines');
if button == 1
% Make up a custom colormap specifying the color for each bar series.
barColorMap(1,:) = [.2 .71 .3]; % Green Color for segment 1.
barColorMap(2,:) = [.25 .55 .79]; % Blue Color for segment 2.
barColorMap(3,:) = [.9 .1 .14]; % Red Color for segment 3.
barColorMap(4,:) = [.9 .9 .14]; % Yellow Color for segment 4.
% I have not defined any more than 4 colors in this demo.
% For any number of bars beyond 4, just make up random colors.
if numberOfBars > 4
barColorMap(5:numberOfBars, 1:3) = rand(numberOfBars-4, 3);
end
elseif button == 2
% Example of using colormap with random colors
barColorMap = rand(numberOfBars, 3);
elseif button == 3
% Example of using pre-defined jet colormap
barColorMap = jet(numberOfBars);
elseif button == 4
% Example of using pre-defined Hot colormap
barColorMap = hot(numberOfBars);
else
% Example of using pre-defined lines colormap
barColorMap = lines(numberOfBars);
end
% Plot each number one at a time, calling bar() for each y value.
for b = 1 : numberOfBars
% Plot one single bar as a separate bar series.
handleToThisBarSeries(b) = bar(x(b), y(b), 'BarWidth', 0.9);
% Apply the color to this bar series.
set(handleToThisBarSeries(b),'FaceColor', barColorMap(b,:));
% Place text atop the bar
barTopper = sprintf('y(%d) = %.3f', x(b), y(b));
text(x(b)-0.2, y(b)+3, barTopper, 'FontSize', 15);
hold on;
end
% Fancy up the graph.
grid on;
caption = sprintf('Data plotted in %d barseries, each with a different color', length(y));
title(caption, 'FontSize', fontSize);
xlabel('x', 'FontSize', fontSize);
ylabel('y', 'FontSize', fontSize);
% Restore the x tick marks.
set(gca, 'XTickMode', 'Auto');
% set(gca, 'XTickLabels', xTickLabels);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off');
  2 Kommentare
shaz
shaz am 1 Jan. 2013
Bearbeitet: shaz am 1 Jan. 2013
how can we have 4 bars with four different colors
since i am using bar(x,y)
Image Analyst
Image Analyst am 1 Jan. 2013
See demo code I added above.

Melden Sie sich an, um zu kommentieren.


Ray Johnston
Ray Johnston am 31 Jan. 2019
I have a quetion.
I want to keep my bars in order with respect to the x-axias, but I want different colors for each. I wrote this script:
%To keep the x-values in order as opposed to scaled
x = categorical(["1492" "1497" "1496" "1200" "980"]);
x = reordercats(x,{'1492','1497','1496','1200','980'});
%Define y-values
y = [0.183 0.288 0.471 0.854 0.596];
bar(x,y);
hold on;
bar(x(1),y(1));
set(bar(1),'FaceColor','b');
bar(x(2),y(2));
hold on;
set(bar(2),'FaceColor','g');
bar(x(3),y(3));
hold on;
set(bar(3),'FaceColor','y');
bar(x(4),y(4));
hold on;
set(bar(4),'FaceColor','r');
bar(x(5),y(5));
hold on;
set(bar(5),'FaceColor','m');
hold off
I keep getting a bar graph with 1492 (x(1),y(1) in magenta, and all the colors worng. Any help would be greatly appreciated. I have an unusual dataset, as it is not time-based nor regular.
Thanks!

Dr. Murtaza Khan
Dr. Murtaza Khan am 16 Mär. 2019
Bearbeitet: Dr. Murtaza Khan am 16 Mär. 2019
mydata=rand(1,10)
color= ['r','g','b','k'];
figure, hold on
% % if data is more than colors then colors will be repeated
m = length(color);
for k = 1:length(mydata)
i = mod(k-1,m); %%i is remainder after division of k-1 by m
i = i+1;
h=bar(k,mydata(k));
set(h,'FaceColor',color(i));
end

Kategorien

Mehr zu Data Distribution Plots finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by