MATLAB: A “pareto” plot followed by a “plot” command using the same axis handle deletes all the graphical objects in the current figure

axishandleMATLABparetoplot

When I plot with any of the plot functions ("loglog", "bar", "plot" etc.) on the same axis on which a "pareto" plot was generated, why does all the other figure objects gets deleted?
 

Best Answer

The "parteo" function using an axis handle generates a plot with two axes, each of which needs to be handled correctly in order to generate another plot on the same original axis.  If the second axis is not handled properly, a subsequent plot commands with the original axis would lead MATLAB to delete all other figure objects in the current figure.  This can be better understood with the help of following example-
Suppose on a figure there are two subplots (two axes objects), and a "pareto" plot is generated on the second axis using the following commands -
>> figure
>> ax1 = subplot(2,1,1) ;
>> ax2 = subplot (2,1,2) ;
>> pareto(ax2, rand(1,1000));
If the current figure objects are inspected using "findobj", it can be seen that current figure has 3 axes objects instead of 2. 
>> findobj(gcf)
ans =
  6×1 graphics array:
  Figure    (1)
  Axes
  Axes
  Axes
  Line
  Bar
Now, if another plot is generated using the axis handle 'ax2' on second subplot and the figure objects are inspected, it is observed that all other figure objects except the ones associated with current plot gets deleted. The axis 'ax1' does not exist anymore.
>> plot(ax2, 1:10)
>> findobj(gcf)
ans =
3×1 graphics array:
Figure (1)
Axes
Line
This is happening because the third axis of "pareto" is not handled before plotting on axis 'ax2', and MATLAB deletes all the figure objects to generate the subsequent plot.  Of the many possible solutions, one way to generate the following plots after "pareto" is to "hold" the axis 'ax2', delete the additional "pareto" axis, remove the "hold'"on 'ax2' and then plot using the axis handle.  The following code describes the workaround
>> hold (ax2)
Current plot held
>> fig_obj = findobj(gcf, 'Type', 'Axes');
>> delete(fig_obj(1));
>> hold (ax2)
Current plot released
>> plot(ax2, 1:10)
This successfully plots the new plot on the same axis as the "pareto" was plotted.  Please note that we should delete the additional axis of the "pareto" plot only, and not any other axis in the figure.