Plotyy Display Gridlines Axis
24 views (last 30 days)
Show older comments
I am using plotyy, I managed to show the grid for the function on the left using 'grid on', but how do I show the gridlines using the function on the right?
1 Comment
DadPunsAreBadPuns
on 17 Jul 2020
Whyyaxis question? Because you wanted an answer!
Since plotyy is no longer recommended, here's a workaround with yyaxis. You can make it into your own %<UserProfile>%\Documents\MATLAB\ folder for future use.
close all; clear all; clc;
% Setup dummy data
x = 1:10;
y = x;
% Setup colors
line_color = [ 1 , 0 , 0 ]; % Red
alpha_value = 0.15;
grid_line_color = [ line_color , alpha_value ]; % Transparent red
% Create a figure and plot the dummy-data line
fig1 = figure(1);
ax1 = axes;
hold on;
yyaxis right;
line1 = plot( x , y , '-' , 'Color' , line_color );
myYGridHandles = plotRightYGrid( ax1 , grid_line_color );
function [ gridLineHandles ] = plotRightYGrid( axh , grid_line_color )
% Made into a function if you'd like to reuse in the future.
% The following is possibly redundant, but performed for sanity's sake
axes( axh );
yyaxis right;
% Acquire the x-axis limits to get the grid-lines' extents
xlim_right = xlim;
% Acquire the tick mark values; these can be default or specified by user
y_ticks_right = get( gca , 'YTick' );
% Plot the major Y-right grid lines
for( j = 2 : ( length( y_ticks_right ) - 1 ) )
gridLineHandles(j) = plot( [ xlim_right(1) , xlim_right(2) ] , ...
[ y_ticks_right(j) , y_ticks_right(j) ] , ...
'-' , 'Color' , grid_line_color );
end
end
Accepted Answer
Jonathan LeSage
on 17 Oct 2013
Edited: Jonathan LeSage
on 17 Oct 2013
You can select the second axis handle for the data plotted with respect to the right y-axis. If you define an output for the plotyy function, the output variable will contain the figure axes handles in a vector. You can then use the set function to define the 'Xgrid' and 'Ygrid' states as 'on'.
For example:
% Outputs of the plotyy are the axes handles (in a vector) and each line handle
[haxes,hline1,hline2] = plotyy(t,z1,t,z2,'semilogy','plot');
% Turn the grid for the second axis on
set(haxes(2),'Xgrid','on')
set(haxes(2),'Ygrid','on')
Check out the documentation for more information on the set function:
2 Comments
James Ryan
on 26 Feb 2018
plotyy is no longer recommended in the docs, which now recommend yyaxis. Is there an updated way to accomplish this with yyaxis, which has no output?
Thanks! By the way, I'm not complaining about the original answer. I assume it was good at the time.
Cris LaPierre
on 19 Dec 2018
It does not appear to be possible to add a grid line to the right axis when plotting using yyaxis.
Grid Lines
Grid lines correspond with the tick mark locations along the left y-axis.
More Answers (0)
See Also
Categories
Find more on Two y-axis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!