Prevent Non-integer Tick Marks

8 次查看(过去 30 天)
I am writing a library that includes function that plots discrete data that always aligns with integers on the x-axis. Including tick marks at decimal values between integers is potentially confusing to users so I'd like to hide them. How can I prevent MATLAB from adding ticks at non-integer values?
For given axes, it is easy enough to remove all of the tick non-integer tick marks, as follows:
ax = gca();
xtick_values = ax.XTick;
integer_indices = fix(xtick_values) == xtick_values;
ax.XTick = xtick_values(integer_indices);
The problem with this, is that it does not update if a user drags the plot to a region where there are no tick marks.
I would prefer a solution that is compatible back to MATLAB R2014b, but if that's too difficult, I'll take what I can get.

采纳的回答

Paul Wintz
Paul Wintz 2022-7-2
I was able to develop the following solution to my question:
clf
ax = gca;
xlim([0, 3]) % Create an axes with x in [0, 3]. This has ticks at every 0.5.
% Hide non-integer ticks.
removeNonintegerTicks(ax.XAxis)
% Setup a callback to handle when the limits change.
ax.XAxis.LimitsChangedFcn = @removeNonintegerTicks;
function removeNonintegerTicks(ruler,~)
% Make ruler value mode automatic, momentaryily, (if it isn't already)
% so that the location of the tick marks are recomputed.
ruler.TickValuesMode = 'auto';
% Now, hide any tick marks that are not integers.
tick_values = ruler.TickValues;
% Sometimes the '0' tick mark is off by ~1e-17, so we use a small range of
% values.
integer_indices = abs(fix(tick_values) - tick_values) < 1e-12;
% Keep only the (approximately) integer values.
ruler.TickValues = tick_values(integer_indices);
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Object Properties 的更多信息

产品


版本

R2014b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by