user2814826
user2814826

Reputation: 11

Multiple axis: using plot vs. line

I have 2 sets of data I want to plot on the same graph.

First an histogram:

hist(data1);
ax1 = gca;

I set the next set of axis, y on the other side

ax2 = axes('Position',get(ax1,'Position'),...
    'XAxisLocation','bottom',...
    'YAxisLocation','right',...
    'Color','none',...
    'XColor','k');

If I use line() to plot my data it works:

line(data2a, data2b, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2);

But if I use plot(), the histogram is erased and both axis appear on the left.

plot(ax2, data2a, data2b); 

Can somebody figure out why the second axis is not valid for plot()?

Upvotes: 1

Views: 98

Answers (1)

sebastian
sebastian

Reputation: 9696

You should check out doc hold.

Axes in MATLAB have the 'NextPlot' property, specifying what to do when a new plot-function is issued on this axis. The default for 'nextplot' is replace, meaning that before anything new is drawn, existing plots are erased. Using hold(ax, 'on') or set(ax, 'nextplot', 'add') you can specify that new plots are added to the existing ones, instead of replacing them.

The reason that line and plot behave differently is, that high level functions (like plot) respect this axis property, while low-level functions like line, patch and others do not. They are added to axis in any case and do not remove existing children.

EDIT: Now I'm noticing that ax2 should be empty in your case - maybe just try the above nevertheless ;)

Upvotes: 4

Related Questions