How can I change the color of bars in bar graph? - matlab

I'd like to create a bar graph where I change the color of some bars.
The code for my bar graph is the following:
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)
I want the first six bars to be black and the last 6 bars to be blue, but I have no idea how to do it.

You need to plot them separately (but on the same axes):
bar(1:6,y(1:6),'k')
hold on
bar(7:numel(y),y(7:end),'b')
set(gca,'xtick',1:numel(y))

As the answer from HERE suggests, since the version MATLAB R2017b, you can do so through the CData property. You can find more at THIS documentation page.
Simply put, using the following approach will get you what you need.
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];

The following is adapted from Bar plot with bars in different colors on 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

No need to plot separately, here is the simple solution:
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')
See output

Very late as usual, but there is an easy way to 'trick' matlab.
You first define your colormap (for instance 3 different colors):
mycolors = lines(3) % or just specify each row by hand
Then you plot your bars in the following way:
bar(x,diag(y),'stacked'); % x will be usually defined as x = 1:number_of_bars
colormap(mycolors);
That's all. The magic comes from the diag function together with the 'stacked' tag that makes matlab think you have more data (but they are all 0).

Related

Specifying different colour schemes for different orientations of Polarhistogram in MATLAB

Question
When using polarhistogram(theta) to plot a dataset containing azimuths from 0-360 degrees. Is it possible to specify colours for given segments?
Example
In the plot bellow for example would it be possible to specify that all bars between 0 and 90 degrees (and thus 180-270 degrees also) are red? whilst the rest remains blue?
Reference material
I think if it exists it will be within here somewhere but I am unable to figure out which part exactly:
https://www.mathworks.com/help/matlab/ref/polaraxes-properties.html
If you use rose, you can extract the edges of the histogram and plot each bar one by one. It's a bit of a hack but it works, looks pretty and does not require Matlab 2016b.
theta = atan2(rand(1e3,1)-0.5,2*(rand(1e3,1)-0.5));
n = 25;
colours = hsv(n);
figure;
rose(theta,n); cla; % Use this to initialise polar axes
[theta,rho] = rose(theta,n); % Get the histogram edges
theta(end+1) = theta(1); % Wrap around for easy interation
rho(end+1) = rho(1);
hold on;
for j = 1:floor(length(theta)/4)
k = #(j) 4*(j-1)+1; % Change of iterator
h = polar(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
set(h,'color',colours(j,:)); % Set the color
[x,y] = pol2cart(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
h = patch(x,y,'');
set(h,'FaceColor',colours(j,:),'FaceAlpha',0.2);
uistack(h,'down');
end
grid on; axis equal;
title('Coloured polar histogram')
Result

plotting bar chart make negative bars different colour to positive bars

I am plotting a bar chart in Matlab. I would like to know if it is possible to base the colours of the bars based on a simple condition? I would like all the positive bars to be say blue and the negative ones to be red. If this is possible can you please tell me how I can going about doing this in MATLAB?
Yes, it's possible, see this solution on MATLAB Central.
Here's some example code extracted from this. The third column of the data is used to determine which colour to apply to each bar. In your case, you just need to check whether each value is positive or negative and change the colour accordingly.
data = [.142 3 1;.156 5 1;.191 2 0;.251 4 0];
%First column is the sorted value
%Second column is the index for the YTickLabel
%Third column is the reaction direction
% Data(1,3) = 1 -> bar in red
% Data(1,3) = 0 -> bar in blue
% For each bar, check direction and change bar colour
H = data(:, 1);
N = numel(H);
for i=1:N
h = bar(i, H(i));
if i == 1, hold on, end
if data(i, 3) == 1
col = 'r';
else
col = 'b';
end
set(h, 'FaceColor', col)
end
Alternatively, you could include your conditions (here data>0 and data<0) as follows:
data = rand(8,1) - .5;
figure(1);
clf;
hold on;
bar(data.*(data>0), 'b');
bar(data.*(data<0), 'r');

How do I plot values from a struct as different lines so I can control their color Matlab?

What I want:
Different coloured points on a plot and to have the points in a legend with their respective colours.
I tried this:
I have created a struct which contains x, y values of points. With these points I hope to plot points on an image so I can see where they are. However, as I'm using a struct I can't get the plot to make the points in different colours. With the for loop I tried to coax matlab in creating multiple plots, and hopefully different lines, which I could then assign to different colours of my choosing.
Code:
img = imread('retinotopische map V1M Base clean.bmp');
hold on;
image([0.825 4.61],[-2.85 ,-8.25],img);
for A = 1:B
plot( [c(A).Lateral],[c(A).Bregma],'o','MarkerSize',10);
plot( [c(A).Lateral],[c(A).Bregma],'.','MarkerSize',10);
end
If you just want different colors, the solution is easier than you would expect:
Replace hold on with hold all and matlab will automatically use the next color.
Edit: If you start a new plot, you may need to call hold off and hold all again to get the right starting position.
You can change the colour using the 'Color' option:
img = imread('retinotopische map V1M Base clean.bmp');
hold on;
image([0.825 4.61],[-2.85 ,-8.25],img);
for A = 1:B
plot( [c(A).Lateral],[c(A).Bregma],'o','MarkerSize',10, 'Color', [A/B, 0, 1 - A/B]);
end
'Color' lets you specify an RGB triple like [1 0 0] for red for example. You can use this to plot whatever colors you want. My example will plot them in like a gradient but you could also have totally different colours using say rand(1, 3) to get the triple? Or else make a colour matrix where you specify the exact order of colours you want like:
MyColours = [1 1 0;
0 0 1;
1 0 0;
0.5 0.2 0.9]; %etc...
and then in your for loop:
plot( [c(A).Lateral],[c(A).Bregma],'o','MarkerSize',10, 'Color', MyColours(A, :));

Setting colors for plot function in Matlab

I would like to be able to choose the colors for a multiline plot but I can not get it. This is my code
colors = {'b','r','g'};
T = [0 1 2]';
column = [2 3];
count = magic(3);
SelecY = count(:,column),
plot(T,SelecY,'Color',colors{column});
For some reason I couldn't get it to work without using a handle, but:
h = plot(T,SelecY);
set(h, {'Color'}, colors(column)');
Works for me.
You can only specify one color at a time that way, and it must be specified as a 3-element RGB vector. Your three routes are:
Loop through and specify the colors by string, like you have them:
hold on
for i=1:size(SelecY, 2)
plot(T, SelecY(:,i), colors{i});
end
Using the RGB color specification, you can pass the colors in via the 'Color' property, like you were trying to do above:
cols = jet(8);
hold on
for i=1:size(SelecY, 2)
plot(T, SelecY(:,i), 'Color', cols(i,:));
end
Also using the RGB way, you can specify the ColorOrder up front, and then let matlab cycle through:
set(gca, 'ColorOrder', jet(3))
hold all
for i=1:size(SelecY, 2)
plot(T, SelecY(:,i));
end
For setting colors after the fact, see the other answer.

Matlab Ploting with different color for iso-surface

I was trying use the code shown below to plot in such a way that each iso-surface will be different in color and there will be a color bar at the right. I made a ss(k) color matrix for different colors. Number of iso-surfaces is 10 but I have only 8 colors. That's why I wrote ss(9)='r' and ss(10)='r'.
I need a solution to plot the iso-surface with different color and bar at the right side.
ss=['y','m','c','r','g','b','w','k','r','r']
k=1;
for i=.1:.1:1
p=patch(isosurface(x,y,z,v,i));
isonormals(x,y,z,v,p)
hold on;
set(p,'FaceColor',ss(k),'EdgeColor','none');
daspect([1,1,1])
view(3); axis tight
camlight
lighting gouraud
k=k+1;
end
Another possibility is to draw the patches with direct color-mapping (by setting the property 'CDataMapping'='direct'), while assigning the 'CData' of each patch to an index in the colormap of your choice. This is in fact recommended for maximum graphics performance.
Consider the following example:
%# volumetric data, and iso-levels we want to visualize
[x,y,z,v] = flow(25);
isovalues = linspace(-2.5,1.5,6);
num = numel(isovalues);
%# plot isosurfaces at each level, using direct color mapping
figure('Renderer','opengl')
p = zeros(num,1);
for i=1:num
p(i) = patch( isosurface(x,y,z,v,isovalues(i)) );
isonormals(x,y,z,v,p(i))
set(p(i), 'CData',i);
end
set(p, 'CDataMapping','direct', 'FaceColor','flat', 'EdgeColor','none')
%# define the colormap
clr = hsv(num);
colormap(clr)
%# legend of the isolevels
%#legend(p, num2str(isovalues(:)), ...
%# 'Location','North', 'Orientation','horizontal')
%# fix the colorbar to show iso-levels and their corresponding color
caxis([0 num])
colorbar('YTick',(1:num)-0.5, 'YTickLabel',num2str(isovalues(:)))
%# tweak the plot and view
box on; grid on; axis tight; daspect([1 1 1])
view(3); camproj perspective
camlight; lighting gouraud; alpha(0.75);
rotate3d on
I also included (commented) code to display the legend, but I found it to be redundant, and a colorbar looks nicer.
Matlab usually plots different iso-surfaces in different colors automatically, so you don't need to care about that. What kind of bar do you need? A colorbar or a legend? Either way, it is just to use the colorbar or legend function..
%Create some nice data
[x y z] = meshgrid(1:5,1:5,1:5);
v = ones(5,5,5);
for i=1:5
v(:,:,i)=i;
end
v(1:5,3:5,2)=1
v(1:5,4:5,3)=2
%Plot data
for i=1:5
isosurface(x,y,z,v,i)
end
%Add legend and/or colorbar
legend('one','Two','Three','Four')
colorbar
Since the color bar encodes value->color, it is impossible to do what you ask for, unless there is no intersection in z-values between all pairs of surfaces. So the solution below assumes this is the case. If this is not the case, you can still achieve it by adding a constant value to each surface, so to separate the surfaces along the z axis, and eliminate any intersection.
The solution is based on constructing a colormap matrix of piecewise constant values, distributed similarly to the z values of your surfaces. So for example, if you have 3 surfaces, the first has z values between 1 and 10, the 2nd between 11 and 30, and the 3rd between 31 and 60, you should do something like this (I plot in 2D for simplicity)
r = [1 0 0];
g = [0 1 0];
b = [0 0 1];
cmap = [r(ones(10,1),:); g(ones(20,1),:); b(ones(30,1),:)];
z1 = 1:10;
z2 = 11:30;
z3 = 31:60;
figure; hold on
plot(z1,'color',r)
plot(z2,'color',g)
plot(z3,'color',b)
colorbar
colormap(cmap)
More complex colormaps (i.e, more colors) can be constructed with different mixtures of red, green, and blue (http://www.mathworks.com/help/techdoc/ref/colorspec.html)