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
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:
-
Plotting Multiple Lines:
- The
plot3function is used twice to plot two 3D lines. - Each dataset is plotted with different line styles and colors for distinction.
- The
-
Adding the Legend:
- The
legendfunction takes strings corresponding to each dataset, in the same order as the plotting commands. - The first string (
'First Dataset') corresponds to the first call toplot3. - The second string (
'Second Dataset') corresponds to the second call toplot3.
- The
-
Optional Customizations:
- You can customize the legend's location by adding an argument like
'Location', 'northwest'to thelegendfunction. - Use
xlabel,ylabel, andzlabelto label the axes.
- You can customize the legend's location by adding an argument like
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
Related 3d plots Questions & Solutions
Browse All →
Explore similar technical troubleshooting questions and verified MATLAB solutions:
Ready-to-Run MATLAB & Simulink Projects
Browse All Projects →