How do you create a color gradient in Matlab such that you plot a 2D line plot of y=y(x), and you color it using another variable that also depends on x such that z=z(x). A scatter or point plot is also fine by me.
I would also like to have a colormap legend kind of thing showing the color gradient and it's actual representation of z. This stuff is quite common in visualisation tools such as VisIt and ParaView but I could not yet FIGURE it out in Matlab.
Using RGB triplets to change colorsOne can specify colors using a vector that gives the RGB triple where in MATLAB, each of the three values are numbers from 0 to 1. Usually RGB colors have values from 0 to 255. You can use those numbers and divide the vector by 255 to use within MATLAB.
Plot Gradient of FunctionFind the gradient of a function f(x,y) , and plot it as a quiver (velocity) plot. Find the gradient vector of f(x,y) with respect to vector [x,y] . The gradient is vector g with these components. Now plot the vector field defined by these components.
Specify Marker Colors in a Scatter Plot Create a scatter plot of random numbers. Specify the marker size as 75 points, and use name-value arguments to specify the marker outline and fill colors. The MarkerEdgeColor property controls the outline color, and the MarkerFaceColor controls the fill color.
The only way I know of to do this is with a little trick using surf
:
% Create some sample data:
x = cumsum(rand(1,20)); % X data
y = cumsum(rand(1,20)); % Y data
z = 1:20; % "Color" data
% Plot data:
surf([x(:) x(:)], [y(:) y(:)], [z(:) z(:)], ... % Reshape and replicate data
'FaceColor', 'none', ... % Don't bother filling faces with color
'EdgeColor', 'interp', ... % Use interpolated color for edges
'LineWidth', 2); % Make a thicker line
view(2); % Default 2-D view
colorbar; % Add a colorbar
And the plot:
To manipulate the color of the line continuously, you'll want to use surface
.
While at first look, this function looks most useful for plotting 3d surfaces, it provides more flexibility for line coloring than the basic plot
function. We can use the edges of the mesh to plot our line, and take advantage of the vertex colors, C
, to render interpolated color along the edge.
You can check out the full list of rendering properties, but the ones you are most likely to want are
Here's an example adapted from MATLAB Answers post
x = 0:.05:2*pi;
y = sin(x);
z = zeros(size(x)); % We don't need a z-coordinate since we are plotting a 2d function
C = cos(x); % This is the color, vary with x in this case.
surface([x;x],[y;y],[z;z],[C;C],...
'FaceColor','none',...
'EdgeColor','interp');
If a scatter plot is fine, you can use the 4th input to scatter
:
x = -10:0.01:10;
y = sinc(x);
z = sin(x);
scatter(x,y,[],z,'fill')
where z
is the color.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With