legend for plot3 command

Indrajit Roy · Aug 10, 2021 · 2.1K views
Question
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 PhD Expert
Answered Aug 16, 2026

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!

100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!