MATLAB Answers

How can I add a third axis to a plot

94 views (last 30 days)
Heidi Hirsh
Heidi Hirsh on 11 Feb 2020
Commented: Adam Danz on 11 Feb 2020
I made a figure using yyaxis to plot two different kinds of data on the same plot. I want to add a third timeseries with a y-axis unique from the first two. I found the plotyyy function but one of my axes has three unique lines and it looks like plotyyy only allows one set of data per axis. Is there a straightforward way to add a third axis to the plot I already have?
Thank you in advance!
box on
yyaxis left
hold on
plot(MX,pkdosat_ns_1d,'-','color',[.4 .6 .6],'linewidth',2)
plot(MX,DO3_1d,'-','color','b','linewidth',2) %[.4 .4 .4]
ylim([90 450])
% new fronds
yyaxis right
hold on
ylabel('New Fronds')
ylim([-1.5 7])
ax=gca; % make y axes black
x = datenum('June-27-2018'):7:datenum('Oct-3-2018');
set(gca, 'XTick', x);
% set(gca,'XTickLabel','');
Adam Danz
Adam Danz on 11 Feb 2020
After plotting all of the data on the yyaxis, set the xlim and ylim so it doesn't change. That's important.
Let's say the new data you want to add on an independent y axis is called data and you want to scale it to the left yyaxis. Let's say that the values in data range from 0 to 5 but you want it in the middle of the y axis range as shown in the picture you shared.
The following are the basic steps you'll need to take. This is untested (again, I don't have access to Matlab right now).
1) Get the y-axis range for the left yyaxis
yyaxis left
leftAxisRange = ylim();
2) set the desired axis limits for the new data axis
data = 1:5; % Your data values (I'm making these up)
dataAxisRange = [-3 7]; % these are the limits you'd like for the new axes
4) Now you have to scale data to the left yaxis range while factoring in the data axis range.
dataScaled = ((data - dataAxisRange(1)) / range(dataAxisRange)) * range(leftAxisRange) + leftAxisRange(1);
5) plot the data using the left axis
yyaxis left
plot(x, dataScaled)
6) You'll have to add pseudo axis ticks that are really just text objects next to the axes.
xl = xlim();
yTicks = -1:6;
% This next line is the same exact scaling we did above.
yTicksScaled = ((yTicks - dataAxisRange(1)) / range(dataAxisRange)) * range(leftAxisRange) + leftAxisRange(1);
yTickXvals = repmat(xl(1), size(yTicksScaled));
yTickLabels = strsplit(num2str(yTicks));
text(yTickXvals, yTicksScaled, yTickLabels, 'HorizontalAlignment', 'Left')

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!