Shade area in graph for multiple y-axes

7 views (last 30 days)
Hi,
I need to shade an arrea of my graph, namely from x-values 552 to 586. In order to do so I used the following code:
%data_final
min = cell2mat(data_final(:,1));
CGM = cell2mat(data_final(:,2));
CGMi = smooth(CGM);
figure(1)
patch([552 586 586 552], [0 0 max(ylim)*[1 1]], [0.8 0.8 0.8])
yyaxis left
plot(min,CGMi);
HR = cell2mat(data_final(:,3));
HRi = smooth(HR);
yyaxis right
plot(min,HRi);
yyaxis left
title('CGM and HR data for a single day')
xlabel('Minutes')
ylabel('CGM [mmol/L]')
yyaxis right
ylabel('HR [bpm]')
However, this does not seem to work for multiple y-axes. Can anybody help me fix this while keeping the y-axes correct?

Accepted Answer

Steve Eddins
Steve Eddins on 4 Jan 2021
I rearranged your code a bit, putting both of the first two plotting functions (patch and plot) after the call to yaxis left. I also inserted a hold on. Note that if you call patch before calling plot, as you have, then the call to ylim inside the patch input arguments is probably not going to do what you want. Since you want to call patch first, so that the line appears on top of it, you need another way to determine the height of the patch. Anyway, here's what I ended up with.
load data_final
min = cell2mat(data_final(:,1));
CGM = cell2mat(data_final(:,2));
CGMi = smooth(CGM);
figure(1)
yyaxis left
patch([552 586 586 552], [0 0 max(CGMi)*[1 1]], [0.8 0.8 0.8])
hold on
plot(min,CGMi)
HR = cell2mat(data_final(:,3));
HRi = smooth(HR);
yyaxis right
plot(min,HRi);
yyaxis left
title('CGM and HR data for a single day')
xlabel('Minutes')
ylabel('CGM [mmol/L]')
yyaxis right
ylabel('HR [bpm]')

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!