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

10 visualizzazioni (ultimi 30 giorni)
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');

Risposta accettata

Karim
Karim il 6 Mar 2023
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

Più risposte (1)

Star Strider
Star Strider il 6 Mar 2023
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]);
.

Categorie

Scopri di più su 2-D and 3-D Plots in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by