version 1.0.0.0 (2.15 KB) by
Denis Gilbert

PLOTYYY - Extends plotyy to include a third y-axis

PLOTYYY builds upon plotyy to include a third y-axis. It also provides an easy way of labelling all three y-axes at once.

Denis Gilbert (2020). plotyyy (https://www.mathworks.com/matlabcentral/fileexchange/1017-plotyyy), MATLAB Central File Exchange. Retrieved .

Created with
R12.1

Compatible with any release

**Inspired:**
myaxisc, addy_axis, plotyyyerrxy, ploty4.m, plots.m, plotses.m, multiplotyyy, plotyn(varargin)

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

Start Hunting!Create scripts with code, output, and formatted text in a single executable document.

Ariane GiesrieglI have a few issues with the figure placement. It always moves offscreen unless i define set(gcf,'color','w','Position',[0, 0, 1200, 800]); - the zeros are important! If there is not x,y=0 the figure "vanishes". With the zeros it just fills the whole screen (both screens in my case).

Also the second data series is only displayed half, the line is cut off between two data points...

I am using Matlab R2020a

Annkathrin DukornHello everybody I need help with the following problem. I used the script:

%% Auswertung 3-fach;

%PLOTYYY - Extends plotyy to include a third y-axis

%

%Syntax: [ax,hlines] = plotyyy(x1,y1,x2,y2,x3,y3,ylabels)

%

%Inputs: x1,y1 are the xdata and ydata for the first axes' line

% x2,y2 are the xdata and ydata for the second axes' line

% x3,y3 are the xdata and ydata for the third axes' line

% ylabels is a 3x1 cell array containing the ylabel strings

%

%Outputs: ax - 3x1 double array containing the axes' handles

% hlines - 3x1 double array containing the lines' handles

%

%Example:

x=S9780Gesamt.date;

y1=S9780Gesamt.daily_median_weightAVG;

y2=S9780Gesamt.daily_mileageAVG;

y3=S9780Gesamt.daily_mileageMEDIAN;

ylabels{1}='daily_median_weightAVG';

ylabels{2}='daily_mileageAVG';

ylabels{3}='fuel_consumption_per_100_kmMEDIAN';

[ax, hlines] = plotyyy(x,y1,x,y2,x,y3,ylabels);

and updatet the function:

function [ax,hlines] = plotyyy(x1,y1,x2,y2,x3,y3,ylabels)

%PLOTYYY - Extends plotyy to include a third y-axis

%

%Syntax: [ax,hlines] = plotyyy(x1,y1,x2,y2,x3,y3,ylabels)

%

%Inputs: x1,y1 are the xdata and ydata for the first axes' line

% x2,y2 are the xdata and ydata for the second axes' line

% x3,y3 are the xdata and ydata for the third axes' line

% ylabels is a 3x1 cell array containing the ylabel strings

%

%Outputs: ax - 3x1 double array containing the axes' handles

% hlines - 3x1 double array containing the lines' handles

%

%Example:

%x=0:10;

%y1=x; y2=x.^2; y3=x.^3;

%ylabels{1}='First y-label';

%ylabels{2}='Second y-label';

%ylabels{3}='Third y-label';

%[ax,hlines] = plotyyy(x,y1,x,y2,x,y3,ylabels);

%legend(hlines, 'y = x','y = x^2','y = x^3',2)

%

%m-files required: none

%Author: Denis Gilbert, Ph.D., physical oceanography

%Maurice Lamontagne Institute

%Dept. of Fisheries and Oceans Canada

%email: gilbertd@dfo-mpo.gc.ca

%Web: http://www.qc.dfo-mpo.gc.ca/iml/

%April 2000; Last revision: 14-Nov-2001

if nargin==6

%Use empty strings for the ylabels

ylabels{1}=' '; ylabels{2}=' '; ylabels{3}=' ';

elseif nargin > 7

error('Too many input arguments')

elseif nargin < 6

error('Not enough input arguments')

end

figure('units','normalized',...

'DefaultAxesXMinorTick','on','DefaultAxesYminorTick','on');

%Plot the first two lines with plotyy

[ax,hlines(1),hlines(2)] = plotyy(x1,y1,x2,y2);

cfig = get(gcf,'color');

pos = [0.1 0.1 0.7 0.8];

offset = pos(3)/5.5;

%Reduce width of the two axes generated by plotyy

pos(3) = pos(3) - offset/2;

set(ax,'position',pos);

%Determine the position of the third axes

pos3=[pos(1) pos(2) pos(3)+offset pos(4)];

xmin=datenum('07-Jan-2019 00:00:00');

xmax=datenum('17-May-2020 00:00:00');

% %Determine the proper x-limits for the third axes

limx1=[xmin xmax];

limx3=[xmin xmin+1.2*(xmax-xmin)];

% %Bug fix 14 Nov-2001: the 1.2 scale factor in the line above

% %was contributed by Mariano Garcia (BorgWarner Morse TEC Inc)

ax(3)=axes('Position',pos3,'box','off',...

'Color','none','XColor','k','YColor','r',...

'xtick',[],'xlim',limx3,'yaxislocation','right');

hlines(3) = line(x3,y3,'Color','r','Parent',ax(3));

limy3=get(ax(3),'YLim');

%Hide unwanted portion of the x-axis line that lies

%between the end of the second and third axes

line([datestr(limx1(2)) datestr(limx3(2))],[limy3(1) limy3(1)],...

'Color',cfig,'Parent',ax(3),'Clipping','off');

axes(ax(2))

%Label all three y-axes

set(get(ax(1),'ylabel'),'string',ylabels{1})

set(get(ax(2),'ylabel'),'string',ylabels{2})

set(get(ax(3),'ylabel'),'string',ylabels{3})

My function ist based on an Excel spreadsheet. The plot contains three graphs where one has an offset. Now I don't know where the fault is and how I can create three axes without an offset.

eabaker@Iris van der veen & others

To get the x-axis limits the same for all three y-axes, the third has to be adjusted. Basically, take your minimum xlim and add 1.2 times your xlim spread (in math, the difference between max and min). For example, if your xlimits are 3 to 10, your xmin is 3 and xmax is 10. For your 3rd x-axis, your xmax = 3 + 1.2 * (10 - 3). My data was in datetime format and had to be converted to datenum but my code is below:

%Convert desired x-limits to datenum

xmin=datenum('01-Nov-2016');

xmax=datenum('01-Jan-2018');

% Add offset value for third x-axis due to offset in original code that

% allows the 3rd y-axis to show to the right of the 2nd y-axis

xmax3=xmin+1.2*(xmax-xmin);

%Set x-axis limits

set(ax(1),'xlim',[xmin xmax]);

set(ax(2),'xlim',[xmin xmax]);

set(ax(3),'xlim',[xmin xmax3]);

KelvinI forgot to mention in my previous post that the parameter "fac" can be any reasonable number (it doesn't have to be 1.3). After a slight change:

pos = [0.14 0.18 0.55 0.75];

set(ax,'position',pos);

fac = 1.3;

pos3=[pos(1) pos(2) fac*pos(3) pos(4)];

limx1=get(ax(1),'xlim');

limx3=[limx1(1) limx1(1) + fac*(limx1(2)-limx1(1))];

Maria M.Kent WarrenCan someone explain how the offset multiplicative factor of 1/5 on line 48 was determined? I'm trying to figure out how to ensure the 3rd axis is exactly aligned with the other two.

Krushil Modithanks for code.. but anyone can help me with printing the figure??

Charles GreenwoodGood function. I have made a couple of changes to suite my requirements.

-Changed the colour of the 3rd plot line/axis to match Matlab colour scheme.

-Removed nargin statement at the beginning and replaced with an exist statement for identifying empty labels.

-Added a datetick input that enables xaxis to be labeled with datetick string.

See code below.

function [ax,hlines] = plotyyy(x1,y1,x2,y2,x3,y3,ylabels,dateticks)

%PLOTYYY - Extends plotyy to include a third y-axis

%

%Syntax: [ax,hlines] = plotyyy(x1,y1,x2,y2,x3,y3,ylabels)

%

%Inputs: x1,y1 are the xdata and ydata for the first axes' line

% x2,y2 are the xdata and ydata for the second axes' line

% x3,y3 are the xdata and ydata for the third axes' line

% ylabels is a 3x1 cell array containing the ylabel strings

% dateticks string input for datetick e.g. ('dd/mm/yy' or 'yyyy')

%

%Outputs: ax - 3x1 double array containing the axes' handles

% hlines - 3x1 double array containing the lines' handles

%

%Example:

%x=0:10;

%y1=x; y2=x.^2; y3=x.^3;

%ylabels{1}='First y-label';

%ylabels{2}='Second y-label';

%ylabels{3}='Third y-label';

%[ax,hlines] = plotyyy(x,y1,x,y2,x,y3,ylabels);

%legend(hlines, 'y = x','y = x^2','y = x^3',2)

%

%m-files required: none

%Author: Denis Gilbert, Ph.D., physical oceanography

%Maurice Lamontagne Institute

%Dept. of Fisheries and Oceans Canada

%email: gilbertd@dfo-mpo.gc.ca

%Web: http://www.qc.dfo-mpo.gc.ca/iml/

%April 2000; Last revision: 14-Nov-2001

if ~exist('ylabels')

%Use empty strings for the ylabels

ylabels{1}=' '; ylabels{2}=' '; ylabels{3}=' ';

end

figure('units','normalized',...

'DefaultAxesXMinorTick','on','DefaultAxesYminorTick','on');

%Plot the first two lines with plotyy

[ax,hlines(1),hlines(2)] = plotyy(x1,y1,x2,y2);

%determin dateticks (if applicable)

if exist('dateticks')

datetick('x',dateticks)

xtickangle(0)

end

cfig = get(gcf,'color');

pos = [0.1 0.1 0.7 0.8];

offset = pos(3)/5.5;

%Reduce width of the two axes generated by plotyy

pos(3) = pos(3) - offset/2;

set(ax,'position',pos);

%Determine the position of the third axes

pos3=[pos(1) pos(2) pos(3)+offset pos(4)];

%Determine the proper x-limits for the third axes

limx1=get(ax(1),'xlim');

limx3=[limx1(1) limx1(1) + 1.2*(limx1(2)-limx1(1))];

%Bug fix 14 Nov-2001: the 1.2 scale factor in the line above

%was contributed by Mariano Garcia (BorgWarner Morse TEC Inc)

%3rd line colour

lineColor = [0.9290 0.6940 0.1250];

ax(3)=axes('Position',pos3,'box','off',...

'Color','none','XColor','k','YColor',lineColor,...

'xtick',[],'xlim',limx3,'yaxislocation','right');

hlines(3) = line(x3,y3,'Color',lineColor,'Parent',ax(3));

limy3=get(ax(3),'YLim');

%Hide unwanted portion of the x-axis line that lies

%between the end of the second and third axes

line([limx1(2) limx3(2)],[limy3(1) limy3(1)],...

'Color',cfig,'Parent',ax(3),'Clipping','off');

axes(ax(2))

%Label all three y-axes

set(get(ax(1),'ylabel'),'string',ylabels{1})

set(get(ax(2),'ylabel'),'string',ylabels{2})

set(get(ax(3),'ylabel'),'string',ylabels{3})

Sebastian@Patrick Marquardt.

Is that the only reason you downvoted this function?...

A function can never meet all individual needs. That's why one is able to modify them.

Just Label the x axis the same way as the y axes. Go into the function and add:

set(get(ax(1),'xlabel'),'string','YourWantedLabel')

Sebastian@ Neil Stapleton: give the function Matrices instead of vectors. If your vectors are column vectors:

x1 = xline1; y1 = yline1;

x2 = [xline2, xline3]; y2 = [yline2, yline3];

x3 = xline4; y3 = yline4;

[ax,hlines] = plotyyy(x1,y1,x2,y2,x3,y3,ylabels);

In the function you have to modify line 45:

[ax,hlines(1),hlines(2)] = plotyy(x1,y1,x2,y2); --> [ax,hlines(1),hlines(2:3)] = plotyy(x1,y1,x2,y2);

and line 72:

hlines(3) = line(x3,y3,'Color','r','Parent',ax(3)); --> hlines(4) = line(x3,y3,'Color','r','Parent',ax(3));

Patrick MarquardtHow do you label the x-axis in that case???

Danyang LiKai LuoNeil StapletonIs it possible to plot multiple lines for the same axis? I want to plot one function for the first axis, two functions for the second axis, and one for the third. I have not been able to figure out how to do this.

Felix Luthanks

Kapilan TamilselvanHow would you still use features like

hold on;

Kapilan TamilselvanRikIt is a very nice submission, but it doesn't work with datetime values as x. The reason for this is that the xlim property can't be set with datetime values. The annoying workaround is to use datenum instead, and use xtickformat.

Andreas WunschLalIt was helpful for me. Thank you

xlabel('X')

ylabel(ax(1),'Y1');

ylabel(ax(2),'Y2');

ylabel(ax(3),'Y3');

I found these labels are interesting and easy

Hyungil Parkax(3)=axes('Position',pos3,'box','off',...

'Color','none','XColor','k','YColor','r',...

'xtick',[],'xlim',limx3,'yaxislocation','right');

-------------------------------------

'XColor','k' -> 'XColor','none'

--------------------------------------

no longer need hiding unwanted x-axis line.

Vince ClementiGreat code. Question, how would i go about changing the direction of any of these axes plotted using this function? Thanks.

xue dongnice

xue dongwhen i use it,i can't get the figure...I don't understand hou to use the code.

Michelle ALMAKARIHello Thank you for sharing your code. It is really helpful. I tried to modify it to get a logarithmic scale for all x and y axes, but for some reason it works perfectly for the 1st two y axes, but the third one is shifted to the right. Any ideas why or what could be the solution ?

Miguel Angel Ampuero SuarezMiguel Angel Ampuero SuarezThank You Mrs. Denis. It was useful for my work.

Shiva AsapuScott SleegersLijing ChenGreat

Jinghui Wuthank you

rainy caogood，it is useful.

fanliao wanggood

Iris van der VeenHi, I have the same problem that fitou below asked:

I am using the function plotyyy and it works fine.

My problem occurs when change the 'xlim' (set(ax,'xlim',[1,12089]); )

The two first curve extend from the first Y axis to the second Y axis

wich is good because this area corresponds with path area. But the third

curve extends from the first Y Axis to the third Y axis wich is outside

of the path area.

As a result my third curve have a part outside of the path area..

Is anybody know how can I solve this ?

JacquelineshihabsatDear Dr. Denis Gilber

this is really a great function, but I have a problem that I want to draw each function with different labels (dash, solid, itc.).

How could I make this? please help me

rahul ranjanhi, i have extended your code for plotting 4 variable in the same plot. i want to share the code with everyone.

Christian Hoeyliangsai liangKelley SullivanHi. Great code! I'm having trouble with data-tips though. I can get data tips to appear on the 2nd and 3rd axes, but not the first. Any ideas? Thanks!

Sergio MachacaHey, when I run your example, I'm getting an error that says "Out of memory. The likely cause is an infinite recursion within the program." I would appreciate any help with this.

wenzhu wangHow to zoom in or zoom out the added line?

Wei LiWhy my matlab can't implement this function? The warning says that "Error: Function definitions are not permitted in this context." Is it result from the lower version of matlab?

Marc Timmerkarthik adityaTino K.Hey to everyone,

is it possible to have the third plot as a bar? I don't know how to solve the problem.

I would be pleased if somebody can give me an idea.

ElizabethHey, thanks for the code! It works well for me!

However, I can't make the visibility off for the figure. Anyone knows?

Olivia YarneyWorks well except when using view(-90 90) to rotate the plot it only rotates the first two and not the last plot?

Thiago SeilaAndreanyone figure out how to use datetick for x axis with this function?

Daniele MorelloHi, if i would to use this function for "axes" of GUI instead of "figure"?

marc OsheHello, thanks for the function plotyyy. I have a problem with x axis. It gives a far too wide area. How can I restrict the xlim such that I can have yearly axis? I tried to change the 'xlim' (set(ax,'xlim',[2001,2013]); ) but I just get error.

BrighJutaoOlegAna CfitouHello

I am using the function plotyyy and it works fine.

My problem occurs when change the 'xlim' (set(ax,'xlim',[1,12089]); )

The two first curve extend from the first Y axis to the second Y axis

wich is good because this area corresponds with path area. But the third

curve extends from the first Y Axis to the third Y axis wich is outside

of the path area.

As a result my third curve have a part outside of the path area..

Is anybody know how can I solve this ?

wwGreat function! However, I cant seem add an xaxis label. An example would be nice :)

karthikZooming and data cursor problem .. .

only one layer is zooming . . .

what about other 2 layers . . .

plz help

Jakob SieversIt appears my first comment failed to reach the page. Basically, if you want to use this in a subplot structure do:

- comment out "figure(..."

- pos=get(gca,'pos'); instead of pos = [0.1 0.1 0.7 0.8];

- pos(3)=pos(3)-offset; instead of pos(3)=pos(3)-offset/2;

Thanks

Jakob SieversJakob Sieverscorrection to the second point:

I changed from

pos = [0.1 0.1 0.7 0.8];

to

pos=get(gca,'pos');

is what I was trying to say.

Stratosqiong linHi,

First thanks for writing such a useful code. I have to add up to three axis and plotyyy works fine.

But the code only generates in new figure, and I didn't manage to generate the three axes into existing figure despite hard trying. Can you please show me how to solve the problem ?

To force the axes to generate in my existing figure, the code

'figure('units','normalized','DefaultAxesXMinorTick','on','DefaultAxesYminorTick','on')' in plotyyy.m is put in comment; plus, position unit converted in centimeter as is the case in my own figure.

The axis 1 and 2 show up, but not the third axis!!

Please any help would be really appreciated.

Miguel Ignacio Barriosgood, thanks

Wu ZhiyongThanks, very useful!

Can the third line be changed to be a bar plot?

Cheers

Mario LiverpoolVery well done! thank u! :)

Karel CastroCan't use it calling the file from path, but very useful, thanks! Also labels didn't works as is stated in the example.

Hassan Ridoes not plot two x axes, but plotxx is listed as one of the keywords

YI xucannot use in subplot, always generate in a new plot

Izru GarnerEasy to use, and very practical!

Anja NoserLibor Wildalooks realy good

Bejoy MathewsGreat...

Thanks a lot..

But do you know any which can plot 5 axes at once?

Si BettsChitra ParthibanThanks. It is very useful to plot and analysis the online data's together

Lina ChangThanks for coming up with a way of adding additional axes.

robs goldyVery good

Olivier Gsmall and simple but useful