Reputation: 1374
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.
Upvotes: 6
Views: 9116
Reputation: 880259
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
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()
Upvotes: 12