更改轴而不改变数据(Python)

5 投票
1 回答
8299 浏览
提问于 2025-04-18 08:06

我想知道怎么绘制一些数据,然后把这些数据生成的坐标轴去掉,换成一个不同范围的坐标轴。

比如说,我有这样的代码:

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()

这段代码会在一个5x5的图上画出一条线,坐标轴的范围都是从0到5。我想把这个0到5的坐标轴去掉,换成一个范围是-25到25的坐标轴。这样只是改变了坐标轴的显示,但我不想移动任何数据,也就是说,数据的样子和原来的图是一样的,只是坐标轴不同。我知道可以通过移动数据来实现这个效果,但我不想改变数据本身。

1 个回答

11

你可以使用 plt.xticks 来找到标签的位置,然后将这些标签设置为位置值的5倍。这样,底层的数据不会改变,只有标签会改变。

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()

这样做的效果是

enter image description here


另外,你也可以更改刻度格式化器:

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

撰写回答