Louis
Louis

Reputation: 103

Matlab scatter markers bleed over edge of plot

I notice that for scatter plots and for other kinds of plots like bar plots, often the markers bleed over the edge of the plot limits. The picture attached to this question is an example: you can see the plot markers going over the boundary. Can this be prevented, and if so how?

enter image description here

Upvotes: 0

Views: 874

Answers (2)

BaronFiner
BaronFiner

Reputation: 154

This isn't an ideal approach, but I drew white rectangles over the areas outside of the ranges of the axes.

I generate a similar plot:

x=0:.02:1; plot(x,sin(2*pi*x),'o-')

Then, I use the following code:

xl = get(gca,'XLim');
yl = get(gca,'YLim');
set(gca,'clipping','off')
extremes = [xl(2)-xl(1), yl(2)-yl(1)];
rectangle('Position',[xl(1)-extremes(1), yl(2)            , 3*extremes(1),   extremes(2)],'FaceColor',[1 1 1],'EdgeColor','none'); % Top
rectangle('Position',[xl(1)-extremes(1), yl(1)-extremes(2), 3*extremes(1),   extremes(2)],'FaceColor',[1 1 1],'EdgeColor','none'); % Bottom
rectangle('Position',[xl(2)            , yl(1)-extremes(2),   extremes(1), 3*extremes(2)],'FaceColor',[1 1 1],'EdgeColor','none'); % Right
rectangle('Position',[xl(1)-extremes(1), yl(1)-extremes(2),   extremes(1), 3*extremes(2)],'FaceColor',[1 1 1],'EdgeColor','none'); % Left
set(gca,'XLim',xl);
set(gca,'YLim',yl);
set(gca,'box','on')
set(gca,'Layer','top')

This code notes the existing ranges of the axes and draws rectangles outside of them. After the rectangles are drawn, the ranges of the axes are restored, and the axes are brought to the front.

I populated extremes arbitrarily. It could be made larger if the axes region of the figure occupies a much smaller portion, or smaller if there are other axes regions at risk for being overlapped.

Here is the end result.

Upvotes: 0

Suever
Suever

Reputation: 65430

The markers themselves are not affected by the axes Clipping property

Clipping does not affect markers drawn at each data point as long as the data point itself is inside the x and y axis limits of the plot. MATLAB displays the entire marker even if it extends slightly outside the boundaries of the axes.

The "solution" would be to add a small amount of padding around your plot so that the entirety of your marker falls within the axes.

The following pads the x and y range by 1%

xlims = get(gca, 'xlim');
ylims = get(gca, 'ylim');

set(gca, 'xlim', xlims + [-0.01 0.01] * diff(xlims), ...
         'ylim', ylims + [-0.01 0.01] * diff(ylims));

enter image description here

Upvotes: 3

Related Questions