plotting – General way to make a ListPlot with tick labels restricted to integer values? Likewise for a ListLogPlot with tick labels at simple powers of ten


Suppose I want to make a ListPlot of an XY data set for which all the Y values are integers, with the restriction that the tick labels on the Y axis only take integer values. Make note that it doesn’t’ always work out that way in the Automatic case.

How can one create a tick label function or another method to do this?

I don’t necessarily want to change the Y axis plot range from its Automatic value and I’d rather not plot the data twice — once to get the plot range and once again to select the tick marks and tick labels according to my specifications — if I can avoid it because that takes too long.

Similarly, if one of the axes uses a log scale (e.g., ListLogPlot), how can I ensure that it only chooses axis labels that are simple powers of ten rather than a number times a power of ten?

I asked Wolfram Tech Support (WTS) for help finding a solution to this problem, but their offering (set Ticks -> {Automatic, Cases(#, _Integer)}) &(data)) fell short of the mark.

What follows is some test code with example results demonstrating the problem when using Automatic ticks selection and with the solution offered by WTS. Clearly neither one produces an acceptable result in the general case.

Example code:

Module({min, max, data},
  {min, max} = Sort(RandomChoice(Range(30), 2));
  data = RandomInteger({min, max}, 100);
  GraphicsRow({
     ListPlot(data),
     ListPlot(#, Ticks -> {Automatic, Cases(#, _Integer)}) &(data)},
    ImageSize -> Large)
)

Sample result #1.

enter image description here

Same data being plotted, first the default way, second WTS way.

The ideal general solution would produce a plot looking like the first one. I’m OK with unlabeled tick marks in non-integer locations. I absolutely don’t want non-integer tick labels. The Y axis tick marks and labels in the second plot are just weird looking.

Here’s a second example result:

enter image description here

First plot is fine, second one completely unacceptable.

In my third and final example, both plots are bad but for different reasons.

enter image description here

Not in this particular case, but in some cases the default tick labels are only at non-integer values, which is even worse.

The same test code modified for the log scale case shows that the WTS method doesn’t’ work unless elements of the data set just happen to coincide with all the required powers of 10. Furthermore, in the log scale case I’d like a method that is usable for real number data sets, especially those representing a wide range of floating point numbers from one down to machine precision and that obviously requires negative powers of ten.