MATLAB: How to set the grid of the right yyaxis

gridyyaxis

I have a figure that has 2 yyaxis, and I want the grid shown on the right yyaxis. But the command grid on is only effective on the left yyaxis.
Sure I can just plot the lines of the grids, but the lines are on the top of the other lines or patches. The good thing of the grid is that they are always on the bottom layer, while the lines user plotted are on the top layer.
x1=[200, 300, 250, 520, 340];
x2=[0.3, 0.2, 0.12, 0.4, 0.22];
figure;
yyaxis left
bar(x1);
yyaxis right
plot(x2);
grid on
The grid is on the left yyaxis, while I want it to be of the right yyaxis. What should I do?

Best Answer

Another option is to create new right-axis tick positions to match the tick positions on the left:
x1=[200, 300, 250, 520, 340];
x2=[0.3, 0.2, 0.12, 0.4, 0.22];
figure;
yyaxis left
bar(x1)
ytl = get(gca, 'YTick'); % Get Controlling Left Ticks

yyaxis('right');
plot(x2)
ytr = get(gca, 'YTick'); % Get Right Tick Values

ytrv = linspace(min(ytr), max(ytr), numel(ytl)); % Create New Right Tick Values Matching Number Of Left Ticks
ytrc = compose('%.2f',ytrv); % Tick Label Cell Array

set(gca, 'YTick',ytrv, 'YTickLabel',ytrc) % Set New Right Tick Labels

grid on
producing:
.
EDIT — (1 Dec 2020 at 17:48)
To get ticks and tick labels with more rational spacing:
x1=[200, 300, 250, 520, 340];
x2=[0.3, 0.2, 0.12, 0.4, 0.22];
figure;
yyaxis left
bar(x1)
ytl = get(gca, 'YTick'); % Get Controlling Left Ticks
yyaxis('right');
plot(x2)
ytr = get(gca, 'YTick'); % Get Right Tick Values
tinc = diff(ylim)/numel(ytl); % Tick Increment
ytrv = min(ylim):tinc:(tinc*(numel(ytl)+1));
ylim([min(ytrv) max(ytrv)]) % Set New ‘ylim’
ytrc = compose('%.2f',ytrv); % Tick Label Cell Array
set(gca, 'YTick',ytrv, 'YTickLabel',ytrc) % Set New Right Tick Labels
grid on
producing:
.