Plot 3d plot with different colors depending on the X and Y combination
9 views (last 30 days)
Show older comments
I am plotting a 3D plot, (X,Y,Z).
X and Y are indexes from 1 to 44.
I want that the bar plot color of Z depands on the values of X and Y.
For example:
when X =1 and Y = 20 so the Z bar has to be in color green
when X =10 and Y = 40 so the Z bar has to be in color red
when X =42 and Y = 40 so the Z bar has to be in color blue
The array combination of X and Y are stored in varriable IN, OUT.
for example
IN=[1 5 6 7 8 9 2 10....] (22 values)
OUT=[20 44 21 ....] (22 values)
0 Comments
Answers (2)
Cris LaPierre
on 14 Apr 2023
Edited: Cris LaPierre
on 14 Apr 2023
and this Answer: https://www.mathworks.com/matlabcentral/answers/403031-how-do-i-prevent-bar3-shading-the-sides-of-the-bars
Here's the example from that page.
Z = magic(5);
b = bar3(Z);
colorbar
for k = 1:length(b)
zdata = b(k).ZData;
ix=isfinite(zdata(:,1));
zdata(ix,1)=zdata(ix,2);
b(k).CData = zdata;
b(k).FaceColor = 'flat';
end
12 Comments
Daniel
on 14 Apr 2023
You're interested in creating a bar chart where you can individually control the color of each bar, correct?
b = bar(0:5,6:-1:1)
Once you have the handle b, you can set the FaceColor property to 'flat'. This allows you to control the color of each bar individually with the CData property. The CData property has one row per bar, and one column per color.
% Colors are specified as [R G B], where each base color is in the range 0
% to 1.
redColor = [1 0 0];
greenColor = [0 1 0];
blueColor = [0 0 1];
grayColor = [0.5 0.5 0.5];
% You can read the X and Y data of each bar element through XData and
% YData. You can modify the color by changing CData.
% YData is a vector of the same length as your input.
% CData is a matrix with one row per input and one column per color.
b.FaceColor = 'flat';
for idx=1:length(b.XData)
if b.YData(idx) == 1 % Extract elements from YData
b.CData(idx,:) = redColor; % Extract rows from CData
elseif b.YData(idx) == 3
b.CData(idx,:) = greenColor;
elseif b.YData(idx) == 5
b.CData(idx,:) = blueColor;
else
b.CData(idx,:) = grayColor;
end
end
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!