Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add constant-spaced ticks on axes whose lenghts vary? [Python]

To simplify my problem (it's not exactly like that but I prefer simple answers to simple questions):

I have several 2D maps that portray rectangular region areas. I'd like to add on the map axes and ticks to show the distances on this map (with matplotlib, since the old code is with it), but the problem is that the areas are different sized. I'd like to put on the axes nice, clear ticks, but the widths and heights of the maps can be anything...

To try to explain what I mean: Let's say I have a map of a region whose size is 4.37 km * 6.42 km. I want that there is on x-axis ticks on 0, 1, 2, 3, and 4 km:s and on y-axis ticks on 0, 1, 2, 3, 4, 5, and 6 km:s. However, the image and the axes reach a bit further than to 4 km and 6 km, since the region is larger then 4 km * 6 km.

The space between the ticks can be constant, 1 km. However, the sizes of the maps vary quite a lot (let's say, between 5-15 km), and they are float values. My current script knows the size of the region and can scale the image into right height/width ratio, but how to tell it where to put the ticks?

There may be already solution for this problem, but since I couldn't find suitable search words for my problem, I had to ask it here...

like image 645
mmyntti Avatar asked Jun 27 '11 14:06

mmyntti


1 Answers

Just set the tick locator to use matplotlib.ticker.MultipleLocator(x) where x is the spacing that you want (e.g. 1.0 in your example above).

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

x = np.arange(20)
y = x * 0.1

fig, ax = plt.subplots()
ax.plot(x, y)

ax.xaxis.set_major_locator(MultipleLocator(1.0))
ax.yaxis.set_major_locator(MultipleLocator(1.0))

# Forcing the plot to be labeled with "plain" integers instead of scientific notation
ax.xaxis.set_major_formatter(FormatStrFormatter('%i'))

plt.show()

The advantage to this is that no matter how we zoom or interact with the plot, it will always be labeled with ticks 1 unit apart. enter image description here

like image 161
Joe Kington Avatar answered Sep 22 '22 17:09

Joe Kington