Reputation: 15621
I am using Octave 4.2.1 portable under Win 10.
I have several plots in a single chart, with a single y axis, each one created with a plot(...)
sentence.
I want to add a plot in a secondary y axis to this existing plot, not creating from the beginning the two axes with plotyy
, (EDIT) and being able to work all the same, e.g., adding a legend, etc.
What is the correct usage for this?
If I execute
plotyy(x, ysec) ;
or
ax = gca ;
plotyy(ax, x, ysec) ;
I get
error: Invalid call to plotyy. Correct usage is:
-- plotyy (X1, Y1, X2, Y2)
-- plotyy (..., FUN)
-- plotyy (..., FUN1, FUN2)
-- plotyy (HAX, ...)
-- [AX, H1, H2] = plotyy (...)
This shows something similar for Matlab, but I am not sure all code that works with a secondary axis that would be created with plotyy
, will work with an axis created this way as well.
Upvotes: 8
Views: 13732
Reputation: 60761
Here are two options. I've tested these in MATLAB, but I'm pretty sure it'll work in Octave the same way.
Let's start with some random data plotted normally:
% Initial graph
x1 = linspace(0,1,100);
y1 = randn(size(x1));
clf
plot(x1,y1,'k');
% New data
x2 = x1;
y2 = rand(size(x2));
Here we retrieve the data from the current axes (it would be better if you preserved the axes handle from when you made your first plot, of course). We then plot a new figure using plotyy
that contains the old data and the new data.
ax = gca;
h0 = get(ax,'children'); % This is the handle to the plotted line
x1 = get(h0,'xdata'); % Get data for line
y1 = get(h0,'ydata');
cla(ax) % Clear axes
plotyy(ax,x1,y1,x2,y2); % Plot old and new data
Here we use hold on
to prevent the current data from being deleted, then plot the new data with plotyy
that also adds a dummy plot to the left axis (a single point 0,0). We then delete this dummy plot.
It turns out that adding this dummy plot still causes the left axis to change. So this code first preserves the location of the tick marks and the limits, and then applies those again after plotting. It also makes the left axis the same color as the line that was already there.
ax = gca;
yl = get(ax,'ylim');
yt = get(ax,'ytick');
h0 = get(ax,'children');
hold on
[ax,h1,h2] = plotyy(ax,0,0,x2,y2);
delete(h1)
set(ax(1),'ycolor',get(h0,'color'),'ylim',yl,'ytick',yt)
Upvotes: 7