MATLAB: Matching scatter marker size to pixel size

image processingmarkersizepixelspointsscatter

I'm trying to set the size of markers in my scatter plot to the size of a pixel in my plot. At the moment, I'm calculating the marker size using the following code:
% Setting the size of square markers to 1px^2
s=1.0;
currentunits = get(gca,'Units');
set(gca, 'Units', 'Points');
axpos = get(gca,'Position');
set(gca, 'Units', currentunits);
markerWidth = s/diff(xlim)*axpos(3); % Calculate Marker width in points
s = markerWidth^2;
So, I'm adjusting the value of s from 1 px to its size in points^2, which is how the marker size is defined. But the output is not quite giving me what I want:
What's going on here? Why are the marker sizes still smaller than the image sizes?

Best Answer

Scatter & markersize method
This a is a demo for your marker size idea. However, I don't recommend this method (see note below).
axh = axes('XTick',0:1:10,'YTick',0:1:10); % Assumes square axes

grid on
axis equal
xlim([0,10])
ylim([0,10])
hold on
% Get plot size in pixel units
originalUnits = axh.Units;
axh.Units = 'Points';
axSizePix = axh.Position(3:4);
axh.Units = originalUnits;
% Compute square pixel per 1 unit of data
pixPerUnit = axSizePix ./ [range(xlim(axh)),range(ylim(axh))]; %pixels per unit
scatter(axh, 6.5, 7.5, ceil(max(pixPerUnit))^2, 'b', 'Marker','s','MarkerFaceColor', 'flat')
scatter(axh, 3.5, 3.5, ceil(max(pixPerUnit))^2, 'r', 'Marker','s','MarkerFaceColor', 'flat')
Note that as soon as you resize the figure or axes, you'll lose the fit of each marker to the grid!
For that reason, it may be better to add rectangles that are in data units and will therefore resize with the figure and axes.
Rectangle method
% Define your data points
xy = [6.5, 7.5;
3.5, 3.5;
2.5, 7.5];
% Define your colors
colors = [1 0 0;
0 1 0;
0 0 1];
% Create axes
axh = axes('XTick',0:1:10,'YTick',0:1:10); % Assumes square axes
grid on
axis equal
xlim([0,10])
ylim([0,10])
hold on
% Plot rectangles
rh = arrayfun(@(i) rectangle('position',[xy(i,:)-.5, 1, 1], 'FaceColor',colors(i,:),'EdgeColor', 'none'), 1:size(xy,1));
% The rectanlge size [xy(i,:)-.5, 1, 1] is based on a square grid
% with unit size = 1.