Hi all,
I am working on a MATLAB script where I need to add horizontal lines representing the maximum and average values of my data in two subplots. However, despite my attempts, the lines are not appearing throughout the entire graph horizontally.
Here's a simplified version of the script I'm currently using:
% Create a new figure
figure;
% Plot out2.Q_i_ref (Reference Ship Ice Torque) on the upper subplot
subplot(2,1,1);
plot(out2.Q_i_ref, 'r'); % Plot the reference ship ice torque in red
hold on; % Hold the current plot
% Add a legend and lines showing maximum and average values
legend('Reference ship A ice torque');
max_value_refA = max(out2.Q_i_ref);
avg_value_refA = mean(out2.Q_i_ref);
line([1, length(out2.Q_i_ref)], [max_value_refA, max_value_refA], 'Color', 'k', 'LineStyle', '--', 'DisplayName', ['Max Value: ', num2str(max_value_refA, '%.4g')]);
line([1, length(out2.Q_i_ref)], [avg_value_refA, avg_value_refA], 'Color', 'b', 'LineStyle', '--', 'DisplayName', ['Avg Value: ', num2str(avg_value_refA, '%.4g')]);
xlabel('Time [s]');
ylabel('Ice torque [Nm]');
title('Reference ship A ice torque');
grid on;
legend show;
% Plot out.Q_i_nd (New Design Ice Torque) on the lower subplot
subplot(2,1,2);
plot(out.Q_i_nd, 'b'); % Plot the new design ice torque in blue
hold on; % Hold the current plot
% Add a legend and lines showing maximum and average values
legend('New design A ice torque');
max_value_ndA = max(out.Q_i_nd);
avg_value_ndA = mean(out.Q_i_nd);
line([1, length(out.Q_i_nd)], [max_value_ndA, max_value_ndA], 'Color', 'k', 'LineStyle', '--', 'DisplayName', ['Max Value: ', num2str(max_value_ndA, '%.4g')]);
line([1, length(out.Q_i_nd)], [avg_value_ndA, avg_value_ndA], 'Color', 'r', 'LineStyle', '--', 'DisplayName', ['Avg Value: ', num2str(avg_value_ndA, '%.4g')]);
xlabel('Time [s]');
ylabel('Ice torque [Nm]');
title('New design A ice torque');
grid on;
legend show;
Could you please suggest how I can modify the script to ensure that the horizontal lines representing the maximum and average values are visible throughout the entire graph horizontally in both subplots?
Thank you for your assistance!

답변 (2개)

Star Strider
Star Strider 2024년 3월 6일

1 개 추천

See if the yline function will do what you want.
Adam Danz
Adam Danz 2024년 3월 6일

0 개 추천

max_value_refA = max(out2.Q_i_ref);
avg_value_refA = mean(out2.Q_i_ref);
yline(max_value_refA, '--k')
yline(avg_value_refAm '--b')
max_value_ndA = max(out.Q_i_nd);
avg_value_ndA = mean(out.Q_i_nd);
yline(max_value_refA, '--k')
yline(avg_value_refAm '--r')
You could also label the lines
yline(max_value_refA, '--k', 'max')
or use the legend
yline(max_value_refA, '--k', 'DisplayName', 'max')

카테고리

도움말 센터File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품

릴리스

R2023b

태그

질문:

2024년 3월 6일

댓글:

2024년 3월 15일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by