gpt4 book ai didi

python - 如何更改表示数组的图形的轴单位(例如 1 公里的 X 像素)?

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:18 24 4
gpt4 key购买 nike

使用 matplotlib 我能够显示这个数组:

enter image description here

我想更改 x 轴和 y 轴的单位:例如 40 像素匹配 1 公里并每 1 公里(每 40 像素)打一个勾。

我该怎么做?

最佳答案

您可以先通过设置 extent 参数来获取图像的比例。所以如果你知道例如你的图像宽 10.4 公里,高 7.2 公里,你会设置

ax.imshow(data, extent=(0, 10.4 ,0, 7.2))

另一方面,如果您知道 40 个像素等于 1km,您会像这样从图像形状计算范围

y,x = data.shape
res = 40. # = 40 pixels per kilometer
ax.imshow(data, cmap="terrain", extent=(0,x/res ,0,y/res ))

现在这将自动设置刻度的位置,这通常可以防止轴过度拥挤。
如果你想更多地控制刻度,你可以使用通常的方法来放置刻度,例如手动设置它们 ax.set_xticks([1,2,4.5]) 或使用定位器。

下面是一个完整的工作解决方案。

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(360,520)
fig, ax=plt.subplots()

y,x = data.shape
res = 40. # = 40 pixels per kilometer
ax.imshow(data, cmap="terrain", extent=(0,x/res ,0,y/res ))

ax.set_xlabel("distance [km]")
ax.set_ylabel("distance [km]")

# option 1 (you need to know how many ticks to put beforehands)
#ax.set_xticks(range(14))
#ax.set_yticks(range(10))

# option 2 (automatic ticklabel placement)
import matplotlib.ticker
# put a tick every kilometer
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1))

plt.show()

enter image description here

关于python - 如何更改表示数组的图形的轴单位(例如 1 公里的 X 像素)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42925671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com