legend for plot3 command

Illustration
Indrajit Roy - 2021-08-10T10:10:33+00:00
Question: legend for plot3 command

I am going to plot two 3D data with the help of below command lines. How can I insert legend for both the 3D data in a single window? plot3(x,y,z); hold on; plot3(xx,yy,zz);

Expert Answer

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

You can add a legend to your 3D plot using the legend function in MATLAB. To specify legends for the two datasets in your plot3 commands, follow these steps:

Example Code:

 

% Sample data
x = 1:10; y = x.^2; z = sqrt(x);
xx = 1:10; yy = 2*x; zz = log(x);

% Plot the first 3D data
plot3(x, y, z, 'r', 'LineWidth', 2); % Red line
hold on;

% Plot the second 3D data
plot3(xx, yy, zz, 'b--', 'LineWidth', 2); % Blue dashed line

% Add legend
legend('First Dataset', 'Second Dataset');

% Add labels (optional)
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
grid on;

Explanation:

  1. Plotting Multiple Lines:

    • The plot3 function is used twice to plot two 3D lines.
    • Each dataset is plotted with different line styles and colors for distinction.
  2. Adding the Legend:

    • The legend function takes strings corresponding to each dataset, in the same order as the plotting commands.
    • The first string ('First Dataset') corresponds to the first call to plot3.
    • The second string ('Second Dataset') corresponds to the second call to plot3.
  3. Optional Customizations:

    • You can customize the legend's location by adding an argument like 'Location', 'northwest' to the legend function.
    • Use xlabel, ylabel, and zlabel to label the axes.

Output:

This will create a single 3D plot with two lines, and a legend indicating which line corresponds to each dataset. Let me know if you need further clarification!


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!