How do I fill colour on both sides of the sin wave in this graph?

조회 수: 6 (최근 30일)
Bhavjeet Chatha
Bhavjeet Chatha 2023년 3월 6일
답변: Star Strider 2023년 3월 6일
Please help me modify this code so that the area under the sin wave is red and the area above the wave is blue. Half of the area of the graph should be blue and half red. There is a rough image of what im looking for the colour to be filled like. (obviously this isnt an exact sin wave lol). I dont know how i might do this so your help is much appreciated.
% Define the time axis (x-axis)
t = linspace(0, 12, 1000);
% Define the parameters of the sinusoidal wave
midpoint = 7.5;
amplitude = 7.5;
period = 3;
% Create the sinusoidal wave
y = midpoint + amplitude*sin(2*pi*t/period);
% Set the y-axis limits to 0-15
ylim([0, 15]);
% Plot the wave
plot(t, y);
xlabel('Time');
ylabel('Amplitude');
title('Sinusoidal Wave');

채택된 답변

Karim
Karim 2023년 3월 6일
One way to do this is by using the ployshape function from matlab, see below for a demonstration.
% Define the time axis (x-axis)
t = linspace(0, 12, 1000);
% Define the parameters of the sinusoidal wave
midpoint = 7.5;
amplitude = 7.5;
period = 3;
% Create the sinusoidal wave
y = midpoint + amplitude*sin(2*pi*t/period);
% create an initial plot
figure
plot(t, y)
grid on
xlabel('Time')
ylabel('Amplitude')
title('Sinusoidal Wave')
% set up bounds for the regions
y_min = midpoint - amplitude - 1;
y_max = midpoint + amplitude + 1;
% create a region below the sine
x_red = [0 t max(t)];
y_red = [y_min y y_min];
red_region = polyshape(x_red,y_red);
% create a region below the sine
x_blue = [0 t max(t)];
y_blue = [y_max y y_max];
blue_region = polyshape(x_blue,y_blue);
% plot the regions
figure
hold on
plot(blue_region ,'FaceColor','blue' ,'FaceAlpha',0.5)
plot(red_region ,'FaceColor','red' ,'FaceAlpha',0.5)
xlim( [min(t) max(t)])
ylim( midpoint + [-amplitude amplitude])
title('Regions using polyshape')
grid on

추가 답변 (1개)

Star Strider
Star Strider 2023년 3월 6일
Using the patch function —
% Define the time axis (x-axis)
t = linspace(0, 12, 1000);
% Define the parameters of the sinusoidal wave
midpoint = 7.5;
amplitude = 7.5;
period = 3;
% Create the sinusoidal wave
y = midpoint + amplitude*sin(2*pi*t/period);
% Plot the wave
figure
plot(t, y);
hold on
patch([t flip(t)], [ones(size(y))*min(y) flip(y)], 'r') % Fill Below Durve
patch([t flip(t)], [ones(size(y))*max(y) flip(y)], 'b') % Fill Above Curve
hold off
xlabel('Time');
ylabel('Amplitude');
title('Sinusoidal Wave');
% Set the y-axis limits to 0-15
ylim([0, 15]);
.

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by