machinery
machinery

Reputation: 6290

How to move grid lines to background in Matlab?

I'm using Matlab for plotting. Let us plot the following two histograms:

figure;
x = randn(2000,1);
y = 1 + randn(5000,1);
h1 = histogram(x,'FaceAlpha',0.1);
hold on
h2 = histogram(y,'FaceAlpha',0.1);
grid on

The grid lines are not really in the background. How can I move them completely to the background so that no grid lines are visible on top of the bars?

Upvotes: 1

Views: 801

Answers (2)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22215

The grid lines are kinda in the background. Well, almost: they hide when the object is fully opaque, and they display when it's transparent (but unfortunately they don't show as if they're behind the object, like you say -- it's more like they look disabled over the object when it's opaque).

You can trick matlab into doing what you want by creating two axes with identical plots, where the foreground one has axis off and a transparent plot, and the background one has axis on with gridlines and an opaque white object.

Example: (I use old syntax as I only have matlab 2013a on my PC)

x = randn(2000,1);
y = 1 + randn(5000,1);
hist(x);
hold on
hist(y);
hs = findobj(gca, 'Type', 'patch')
set(hs(2),'FaceAlpha',0.1)
set(hs(1),'FaceAlpha',0.1)
axis off
ax_front = gca;

ax_back = axes;
hist(x);
hold on
hist(y);
hs = findobj(gca, 'Type', 'patch')
set(hs(1), 'faceColor', 'w')
set(hs(2), 'faceColor', 'w')
grid on

axes(ax_front)

Alternatively you could always just create your own custom 'gridlines' function to have complete control over your gridlines and their placement in your plot.

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112659

The grid lines are in the background, but you can see them because the plotted objetcs have some transparency ('FaceAlpha' less than 1).

To achieve what you want, a trick is to plot each histogram twice: first a version with 'FaceAlpha' set to 1, 'Facecolor' white and 'Edgcolor' equal to 'none', to cover the grid lines; and then the normal version.

figure;
x = randn(2000,1);
y = 1 + randn(5000,1);
histogram(x,'FaceAlpha',1,'Facecolor','w','Edgecolor','none');
hold on
histogram(y,'FaceAlpha',1,'Facecolor','w','Edgecolor','none');
h1 = histogram(x,'FaceAlpha',0.1);
h2 = histogram(y,'FaceAlpha',0.1);
grid on

Upvotes: 2

Related Questions