color individual bar with different colors in bar plot

817 vues (au cours des 30 derniers jours)
shaz
shaz le 1 Jan 2013
Commenté : Frederik le 20 Mar 2024
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

Réponses (5)

Randi Cabezas
Randi Cabezas le 11 Juil 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 le 19 Juil 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 commentaires
Chaymae
Chaymae le 26 Jan 2024
Thank you this has been soo helpful
Frederik
Frederik le 20 Mar 2024
Does not work

Connectez-vous pour commenter.


Image Analyst
Image Analyst le 1 Jan 2013
Modifié(e) : Image Analyst le 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 commentaires
shaz
shaz le 1 Jan 2013
Modifié(e) : shaz le 1 Jan 2013
how can we have 4 bars with four different colors
since i am using bar(x,y)
Image Analyst
Image Analyst le 1 Jan 2013
See demo code I added above.

Connectez-vous pour commenter.


Ray Johnston
Ray Johnston le 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 Ali Khan
Dr. Murtaza Ali Khan le 16 Mar 2019
Modifié(e) : Dr. Murtaza Ali Khan le 16 Mar 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

Catégories

En savoir plus sur Data Distribution Plots dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by