David Archibald
David Archibald

Reputation: 1538

Tick Locations from Data

I'd like to get the tick locations(both major and minor) for a set of data like what you would normally pass into plot.plot([x], y) to plot. The usage for this is to speed up some computationally expensive operations on large data sets by utilizing the fact that doesn't all have to be graphed--because only data points on ticks are used to my understanding, as well as to

The classes in matplotlib.ticker seem promising, AutoLocator and AutoMinorLocator are what are usually used, but logic to choose between AutoDateLocator etc. would fall upon the function. Even worse, TickHelper.create_dummy_axis() won't work for AutoMinorLocator as it needs a proper axis. I've considered just... drawing it, getting the ticks, and then clearing it, but some of the usages makes the most sense to come during drawing, so something that doesn't actually affect the plot would be ideal.

I've managed to create a somewhat working solution primarily created from copying and pasting the relevant sections of AutoMinorLocation and getting the view limits myself, however the process is hacky(honestly not worthy of being looked over) and requires only numbers which has only worked for a subset of what I want. Is there a better solution to this?

Upvotes: 0

Views: 213

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339530

If I understand correctly you would like to get the major and minor tick locations that would be produced on an axis with given view interval.

from matplotlib.ticker import AutoLocator, AutoMinorLocator

v = 3,9

loc = AutoLocator()
loc.create_dummy_axis()
loc.axis.get_scale = lambda: "linear"
loc.set_view_interval(*v)
loc2 = AutoMinorLocator()
loc2.axis = loc.axis
loc.axis.get_majorticklocs = loc


print(loc())
print(loc2())

This prints

[3. 4. 5. 6. 7. 8. 9.]
[3.2 3.4 3.6 3.8 4.  4.2 4.4 4.6 4.8 5.  5.2 5.4 5.6 5.8 6.  6.2 6.4 6.6
 6.8 7.  7.2 7.4 7.6 7.8 8.  8.2 8.4 8.6 8.8]

the first array being the major and the second the minor tick locations.

An alternative is to actually create an Axes and use it without any data and without showing it anywhere.

from matplotlib.axes import Axes
from matplotlib.figure import Figure

v = 3,9

ax = Axes(Figure(), [0,0,1,1])
ax.set_xlim(*v)
ax.minorticks_on()

print(ax.xaxis.get_majorticklocs())
print(ax.xaxis.get_minorticklocs())

prints:

[3. 4. 5. 6. 7. 8. 9.]
[3.2, 3.4, 3.6, 3.8, 4.2, 4.4, 4.6, 4.8, 5.2, 5.4, 5.6000000000000005, 5.800000000000001, 6.2, 6.4, 6.6000000000000005, 6.800000000000001, 7.2, 7.4, 7.600000000
0000005, 7.800000000000001, 8.2, 8.4, 8.600000000000001, 8.8]

Note the difference to the above: Here the minor positions at major positions are cut from the array.

Upvotes: 1

Related Questions