5

How could I plot some data, remove the axis created by that data, and replace them with axis of a different scale?

Say I have something like:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim([0,5])
plt.ylim([0,5])
plt.plot([0,1,2,3,4,5])
plt.show()

This plots a line in a 5x5 plot with ranges from 0 to 5 on both axis. I would like to remove the 0 to 5 axis and say replace it with a -25 to 25 axis. This would just change the axis, but I don't want to move any of the data, i.e., it looks identical to the original plot just with different axis. I realize this can be simply done by shifting the data, but I do not wish to alter the data.

Novice C
  • 1,344
  • 2
  • 15
  • 27

1 Answers1

11

You could use plt.xticks to find the location of the labels, and then set the labels to 5 times the location values. The underlying data does not change; only the labels.

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim([0,5])
plt.ylim([0,5])
plt.plot([0,1,2,3,4,5])
locs, labels = plt.xticks()
labels = [float(item)*5 for item in locs]
plt.xticks(locs, labels)
plt.show()

yields

enter image description here


Alternatively, you could change the ticker formatter:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

N = 128
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(range(N+1))
plt.xlim([0,N])
plt.ylim([0,N])
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: ('%g') % (x * 5.0)))
plt.show()

enter image description here

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • This is great and works for my mock question. But when I implement it in my code there is an issue. Instead of ylim and xlim being [0,5] I have [0,128]. In the case of stretching it by 5, I would like the graph to cut off at 640 which is 128*5, but it continues the plot all the way out to 700. Why is that? – Novice C May 31 '14 at 00:49
  • Resolved my issue with the idea of using plt.xticks(), so thank you very much for your help. Will mark as closed, however my question in the previous comment is still unanswered. – Novice C May 31 '14 at 01:00
  • 1
    I don't know the specific reason why that happens, but I've posted a workaround using `FuncFormatter` instead of `xticks`. – unutbu May 31 '14 at 01:04