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

13 ビュー (過去 30 日間)
Bhavjeet Chatha 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 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 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 Center および File Exchange2-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