How to plot several sets (in different colours) with stem3-plotting function?

Illustration
Jouni Lohikoski - 2022-10-31T10:39:56+00:00
Question: How to plot several sets (in different colours) with stem3-plotting function?

So I have several line array A which has columns [x, y, val1, val2]. For example, I want to have a single stem3-plot, where val1s are red and val2s are blue.   stem3(A(:, 1), A(:, 2), A(:, 3), 'red') % Will plot vals1 in red.   But how to get then vals2 in colour blue to the same stem3-plot? Tried something similar which works with 2D-stem:  ("Plot Multiple Data Series"), but it didn't work stem3(A(:, 1), A(:, 2), [A(:, 3), A(:, 4)]); "Error using stem3. The length of X must match the number of columns of Z."   stem3(A(:, 1), A(:, 2), [A(:, 3); A(:, 4)]); "Error using stem3. X and Y must be same length as Z or the lengths of X and Y must match the size of Z."

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

The stem3 function in MATLAB creates 3D stem plots, but it does not directly support plotting multiple sets of values with different colors in a single call. To achieve your goal of plotting val1 in red and val2 in blue on the same 3D plot, you can call stem3 twice and use hold on to combine the plots.

Here’s how you can do it:

Example Code:

 

% Example data
A = [1, 1, 10, 15;
     2, 2, 20, 25;
     3, 3, 30, 35];

% Extract columns for clarity
x = A(:, 1); % X-coordinates
y = A(:, 2); % Y-coordinates
val1 = A(:, 3); % First set of Z-values
val2 = A(:, 4); % Second set of Z-values

% Plot val1 in red
stem3(x, y, val1, 'r', 'LineWidth', 1.5); % 'r' specifies red color
hold on;

% Plot val2 in blue
stem3(x, y, val2, 'b', 'LineWidth', 1.5); % 'b' specifies blue color

% Add labels and title
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('Stem3 Plot with Multiple Colors');

% Turn grid on for better visualization
grid on;

% Optional: Adjust view angle
view(3); % Default 3D view

Explanation:

  1. Separate Calls to stem3:

    • First, plot val1 values in red using 'r'.
    • Then, plot val2 values in blue using 'b'.
  2. Use hold on:

    • This allows the second stem3 plot to be added to the existing figure without overwriting it.
  3. Customization:

    • Adjust line width, marker size, or colors for better distinction.
    • You can use RGB triplets (e.g., [0, 0, 1] for blue) if you need more precise color control.
  4. Grid and View:

    • Adding a grid and adjusting the view can make the plot easier to interpret.

Output:

The resulting 3D stem plot will have:

  • Red stems corresponding to val1.
  • Blue stems corresponding to val2.

If you need further customization or encounter any issues, feel free to ask!


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!