Matlab: Set bar chart colours - matlab

I have a set of values and a bunch of corresponding colours. The colours are dependent on the x labels but they are already in the correct order. How do I plot the bar chart such that the colours correspond to the correct bars. For example...
y= [2 4 12 7 15]'
bar_colour={'b';'b';'g';'r';'k'}
hp=bar(y,bar_colour{:})
At the moment, all the bars are in one colour.

In this case I think a loop is justified:
y = [2 4 12 7 15]'; %'
bar_colour = {'b';'b';'g';'r';'k'};
hold on
for n = 1:numel(y)
bar(n, y(n),bar_colour{n});
end

Related

How to create color transparency gradient for multiple data sets in scatter plot with color determined by third variable in MATLAB

I have scatter plots that each have two sets of data points they are plotting. Each set has its own color but I'd like the points to have different transparency degrees in a gradient determined by a third variable.
Here is some sample code:
tbl = [3 2 1 2 0; 5 6 4 4.5 100; 7 9 8 7.5 250];
c = [0 0.4470 0.7410; 0.6350 0.0780 0.1840];
s = scatter(tbl(:,[1,3]),tbl(:,[2,4]),[],c,"filled");
The x values of each set are tbl columns 1 and 3, the y values are columns 2 and 4. The two colors are defined by "c". I'd like c to vary in transparency based on tbl column 5, so the points get darker from 0 to 250. Currently, they are all the same transparency value within each data set.
Thanks for any suggestions! I'm using MATLAB R2021b.

Matlab bars: changing the color of the bar and the space between bars and axes

I have a tricky question, which I think cannot be simply answered.
I have a large data table and want to save bar charts for each 2 corresponding mean values. I already did that with "for loop", but I cannot set different colors to my bars and cannot set proper spaces between bars and axes.
That's the simplest example:
k = [2 5]
bar(k)
Matlab thinks about those data [2 5] as about one "group" and it does not give a possibility of changing color for only one bar.
Of course, when we have different "groups", colors are changeable.
y = bar([1 2 3; 4 5 6]);
y(2).FaceColor = 'red';
But what about my example? I need only two bars, and I need to color them differently. Also, I want to set a small space between each bar and the axes (and again with two bars it is not that simple, and I cannot use "bar width" because that doesn't give me what I really want).
Does anyone know how to get around this?
Thanks for any reply!
Mary
A good trick could be add zero column for each group:
k = [2 5;0 0];
bar(k,'grouped')
UPDATE
Another solution to have different color could be using location in bar:
k = [2 5];
figure(1);
hold on;
h=bar(1,k(1));
set(h,'FaceColor','k');
h=bar(2,k(2));
set(h,'FaceColor','b');
hold off
As far as I know, this requires the use of a custom bar plot, since Matlab's barplots use dynamic colormaps. Personally, I like the GRAMM toolbox for all these customizations: [GRAMM on file-exchange] [GRAMM on github].
Here's an example:
x = [1 2];
y = [1 1.5];
c = x;
custom_map = ...
[1 0.3673 0.4132;
0 0.7375 0.8344];
clear g
g(1,1)=gramm('x',x,'y',y,'color',c);
g(1,1).geom_bar('width',0.2);
g(1,1).set_title('Width = 0.2');
g(1,2)=gramm('x',x,'y',y,'color',c);
g(1,2).geom_bar('width',0.8);
g(1,2).set_title('Width = 0.8');
g.set_names('y','','x','');
g.set_color_options('map',custom_map);
g.axe_property('YTick',[],'LineWidth',1,'YColor',[1 1 1],'XLim',[0.5 2.5],'XTick',[1 2])
figure('Position',[100 100 600 300]);
g.draw();
The histogram function is one option that will easily handle the spacing and x-axis labeling, but you'll have to plot each bar separately to independently control the colors:
k = [2 5];
histogram('Categories', {'ONE'}, 'BinCounts', k(1), 'BarWidth', 0.8, ...
'FaceAlpha', 1, 'FaceColor', [0 0.4470 0.7410]);
hold on;
histogram('Categories', {'TWO'}, 'BinCounts', k(2), 'BarWidth', 0.8, ...
'FaceAlpha', 1, 'FaceColor', [0.8500 0.3250 0.0980]);
Here is an option to workaround this. You can use diag(k) to create a 2*2 matrix with all zeros except the main diagonal that will be with your values, and Matlab will read it as 2 different groups. Then you change the Xdata of the 'dummy' bars (which you don't see but take some space on the x axis to nan so Matlab will ignore it.
k = [2 5];
b = bar(diag(k));
set(b,{'XData'},{[1 nan],[nan 1]}); % remove the group you don't want
set(gca,{'xticklabel','XTick'},{{'ONE','TWO'},[0.85 1.15]});
b(2).FaceColor = 'r'; % choose a different color
The result:
And if you want to generalize this to more groups (here it's 5):
k = 1:5;
data = diag(k);
xdata = eye(numel(k))./eye(numel(k)); % a martix of nan with 1 on the main diagonal
b = bar(diag(k));
% remove all data except one bin in all groups:
set(b,{'XData'},mat2cell(xdata,ones(size(data,1),1),size(data,2)))
X = xlim; 5 get x-axis limits
w = (1-X(1))/(numel(k)/2); % calculate the width of one bin
set(gca,'XTick',X(1)+w/2:w:X(2)) % set the X ticks to the center of the bins
set(gca,'xticklabel',{'ONE','TWO','THREE','FOUR','FIVE'}); % set the labels
set(b,{'FaceColor'},mat2cell(lines(numel(k)),ones(size(data,1),1),3)); % set the colors
and you get:
And finally, if you want them to 'hover' a little above the x-axis, you can add the following lines:
b(1).BaseLine.Color = 'none'; % remove the base line
ylim([-0.1 max(k(:))]) % shift the bars up a little
and get:

Matlab: Missing labels in bar chart

With Matlab 2012 and 2013, I found that setting XTickLabel on a bar chart only works with up to 15 bars. If there are more bars, labels are missing, as shown below.
Plotting 15 bars:
N = 15;
x = 1:N;
labels = num2str(x', '%d');
bar(x);
set(gca, 'XTickLabel', labels);
Plotting 16 bars:
N = 16;
x = 1:N;
labels = num2str(x', '%d');
bar(x);
set(gca, 'XTickLabel', labels);
For N > 15, it will always only display 10 labels.
Does anyone else experience this? Any work-arounds? I need all labels because I am plotting discrete categories and not a continuous function.
This happens because the tick labels have to match the ticks themselves. In the example you gave with N = 16; and x = 1:N;, MATLAB automatically makes the following XTicks (on your and my machines, at least):
>> xticks = get(gca,'xtick')
xticks =
0 2 4 6 8 10 12 14 16 18
>> numel(xticks)
ans =
10
Just 10 ticks for the 16 different bars. Thus, when you run set(gca, 'XTickLabel', labels); with labels = num2str(x', '%d'); (16 labels), it gives the second figure you showed with the wrong labels and ticks before/after the bars (at positions 0 and 18).
To set a tick label for each bar, you also need to set the ticks to match:
set(gca,'XTick',x) % this alone should be enough
set(gca,'XTickLabel',labels);
Then you will get the desired result:
For whatever reason, 16 seems to be the magic number at which MathWorks decided XTicks should not be drawn for each bar, leaving it up to the user to set them if needed.

MATLAB: Four-part color logo(polygon)

My task is to write MATLAB code to produce a 4-part logo as shown in the screenshot. The top left should be black and the bottom right should be white. The other
two colours should be chosen randomly by the program.
I have taken the following approach:
clear all
clc
close all
x = [1 4 1 4 1 6.5 7 7];
y = [3 4 5.5 5 8 7 8 3];
fill(x,y,'k')
which creates the upper left black part. I wonder if that approach is good enough and if it is, what is the next step. I thought of storing those two variables in a shape object or something (I'm not familiar with Matlab) and rotate it somehow. Could you help me with that?
You don't need to rotate, just use the symmetry
clear all
clc
close all
x = [1 4 1 4 1 6.5 7 7];
y = [3 4 5.5 5 8 7 8 3]-3;
clrs=jet(10);
fill(x,y,'k')
hold on;
fill(2*max(x)-x,y,clrs(round(rand*10),:))
fill(x,-y,clrs(round(rand*10),:))
fill(2*max(x)-x,-y,'w')
The easiest way to do this all this, is to make sure that your center point (i.e. the point where the different colors meet), is positioned at [0,0]. Then a rotation of the figure (by multiple of 90°) boils down to changing the sign of either the x and/or y values of your contour.
If you need the figure to be at a point different from [0 0], just add these coordinates after you did the rotation.
So starting from your code, you can do this:
x = [1 4 1 4 1 6.5 7 7]-7;
y = [3 4 5.5 5 8 7 8 3]-3;
c = [5 6];
col = [0 0 0;
rand(2,3);
1 1 1];
fill( x+c(1), y+c(2),col(1,:)); hold on;
fill(-x+c(1), y+c(2),col(2,:));
fill( x+c(1),-y+c(2),col(3,:));
fill(-x+c(1),-y+c(2),col(4,:)); hold off;
edit: Clarification for the col and c variables.
The variable col contains the colors to be used in rgb style, where each row is a color. rand generates uniformly random numbers in the range [0,1], which is also where the values for the colors are expected to be. In the code above a 2x3 random matrix is generated, so that means 2 random colors which fits perfectly within the col matrix.
The variable c contains the center of your figure. If you look at the plot, the center will be at [5 6] (so 5 along the x axis and 6 along the y axis). You could use two variables instead, but I think that keeping both together in a variable is easier to deal with. I would personally do the same for your x and y variables, as that would allow you to use rotation matrices more easily, but that's just a matter of choice.

Need help in plotting lines between points

I need help in plotting lines between points.
Suppose, I start with creating 6 random points-
x = rand(6,1);
y = rand(6,1);
So my points are (x(1),y(1)), (x(2),y(2)), (x(3),y(3)), (x(4),y(4)), (x(5),y(5)), (x(6),y(6))
Now I want to draw straight lines between the points 1 & 5, 2 & 6, 3 & 4
and plot them in a single diagram. So I get 3 straight lines.
Any help would be highly appreciated.
You can do this with one call to PLOT. If you reshape your x and y data into matrices with each column containing a set of coordinates for one line, then PLOT will draw a different colored line for each column:
index = [1 2 3; 5 6 4]; %# The index to reshape x and y into 2-by-3 matrices
plot(x(index),y(index)); %# Plot the lines
Here are two ways to do this:
First way, using hold on. These lines are separate, i.e if you turn one red, the others will stay blue.
%# plot the first line
plot([x(1);x(5)],[y(1);y(5)]);
hold on %# this will prevent the previous plot from disappearing
%# plot the rest
plot([x(2);x(6)],[y(2);y(6)]);
plot([x(3);x(4)],[y(3);y(4)]);
Second way, making use of the fact that NaN does not get plotted. These lines are grouped, i.e. if you turn one red, all will be red.
%# create array for plotting
xy = NaN(8,2);
%# fill in data
xy([1 2 4 5 7 8],1) = x([1 5 2 6 3 4]);
xy([1 2 4 5 7 8],2) = y([1 5 2 6 3 4]);
%# plot
plot(xy(:,1),xy(:,2))