Shatnerz
Shatnerz

Reputation: 2543

Resetting axes after moving plots around?

I am currently working on a GUI. I would like to have one 'axes' on which I can display multiple plots depending on which the user selects. Currently I have 2 bar plots and 2 surfc plots. I am setting the plots using

set(p1, 'Parent', axes1)

However it looks like when I set a bar plot to an axes that had a surfc there is still a z axis, and the same problem exists the other way around but wuth the lack of a z axis. This sample scripts demonstrates.

figure(1);
a1 = axes();
p1 = bar(1:5);

figure(2);
a2 = axes();
x = [1 2];
z = zeros(2);
p2 = surfc(x, x, z);

set(p1, 'Parent', a2)
set(p2, 'Parent', a1)

What is the best way to go about this?

Upvotes: 0

Views: 111

Answers (1)

Suever
Suever

Reputation: 65430

If you're only working with a single axes, then you can change the view when you change from 3D (for the surfc plot) to 2D (the bar plot).

% Default 2D View
view(hax, 2);

% Default 3D View
view(hax, 3);

If you're allowing a user to toggle between the two, it may be worth not using the default 2D and 3D views, but rather in your button click callback, store the current view in a variable and then when they go back to the plot it keeps any custom viewpoint that the user applied. You can get the current viewpoint with the following:

[az, el] = view(hax);

Mini-rant

Also, in general it is best to assign the parent of your plot objects on construction. Most every graphics object constructor accepts the Parent parameter/value pair. It's a lot more robust that way because then the plot object is never drawn to the wrong axes.

fig1 = figure();
ax1 = axes('Parent', fig1);
p1 = bar(1:5, 'Parent', ax1);

fig2 = figure();
ax2 = axes('Parent', fig2);
p2 = surfc([1 2], [1 2], zeros(2), 'Parent', ax2);

When dealing with MATLAB graphics, I have always found it beneficial to be explicit about the parent when creating axes, plots, and other graphics objects. Never rely on gca, gcf, etc. as those all change if the user somehow clicks in the middle of your rendering.

Upvotes: 1

Related Questions