为了简化我的问题(不完全是这样,但我更喜欢简单的答案而不是简单的问题):
我有几张描绘矩形区域的2D地图。我想在地图上添加轴和刻度来显示地图上的距离(使用matplotlib,因为有旧代码),但问题是区域的大小不同。我想在轴上加上漂亮、清晰的刻度,但地图的宽度和高度可以是任何东西……
为了解释我的意思:假设我有一个区域的地图,它的大小是4.37公里* 6.42公里。我希望在0,1,2,3和4 km:s上有x轴刻度,在0,1,2,3,4,5和6 km:s上有y轴刻度。但是,图像和轴到达的距离比4 km和6 km要远一点,因为该区域大于4 km *6 km。
刻度之间的间距可以是恒定的,1千米。然而,地图的大小差别很大(假设在5-15千米之间),并且它们是浮点值。我当前的脚本知道区域的大小,并且可以将图像缩放到正确的高/宽比例,但是如何告诉它将刻度放在哪里?
这个问题可能已经有了解决方案,但由于我找不到合适的搜索词来解决我的问题,我不得不在这里问它……
发布于 2011-06-28 13:45:25
只需将刻度定位器设置为使用matplotlib.ticker.MultipleLocator(x),其中x是您想要的间距(例如,上面示例中的1.0 )。
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()这样做的好处是,无论我们如何缩放或与绘图交互,它都会被标记为相隔1个单位的刻度。

发布于 2011-06-28 01:03:18
这将给出x轴上当前轴限制内的所有整数值的刻度:
from matplotlib import pylab as plt
import math
# get values for the axis limits (unless you already have them)
xmin,xmax = plt.xlim()
# get the outermost integer values using floor and ceiling
# (I need to convert them to int to avoid a DeprecationWarning),
# then get all the integer values between them using range
new_xticks = range(int(math.ceil(xmin)),int(math.floor(xmax)+1))
plt.xticks(new_xticks,new_xticks)
# passing the same argment twice here because the first gives the tick locations
# and the second gives the tick labels, which should just be the numbers对y轴重复此操作。
出于好奇心:默认情况下,你会得到什么类型的tick?
发布于 2011-06-29 15:21:12
好吧,我试过你的版本,但不幸的是我不能让它们工作,因为有一些缩放和PDF定位的东西让我(和你的代码建议)非常困惑。但是通过测试,我又学到了很多python,谢谢!
我最终设法找到了一个不是很精确但能满足我需求的解决方案。这就是我是如何做到的。
在我的版本中,一公里除以一个适当的整数常量,名为STEP_PART。STEP_PART越大,轴值就越精确(如果太大,轴就会变得混乱,难以读取)。例如,如果STEP_PART为5,则精度为1 km /5= 200 m,刻度线放在每200 m处。
STEP_PART = 5 # In the start of the program.
height = 6.42 # These are actually given elsewhere,
width = 4.37 # but just as example...
vHeight = range(0, int(STEP_PART*height), 1) # Make tick vectors, now in format
# 0, 1, 2... instead of 0, 0.2...
vWidth = range(0, int(STEP_PART*width), 1) # Should be divided by STEP_PART
# later to get right values.为了避免制作太多的轴标签(0,1,2...足够了,0,0.2,0.4...太多了),我们用字符串"“替换非整数的Km值。同时,我们将整数Km值除以STEP_PART以获得正确的值。
for j in range(len(vHeight)):
if (j % STEP_PART != 0):
vHeight[j] = ""
else:
vHeight[j] = int(vHeight[j]/STEP_PART)
for i in range(len(vWidth)):
if (i % STEP_PART != 0):
vWidth[i] = ""
else:
vWidth[i] = int(vWidth[i]/STEP_PART)稍后,在创建图形和轴之后,刻度将以这种方式放置(以x轴为例)。这里,x是图片的实际宽度,是用shape()命令得到的(我不太明白是怎么……在我正在修改的代码中有相当多的缩放和东西)。
xt = np.linspace(0,x-1,len(vWidth)+1) # For locating those ticks on the same distances.
locs, labels = mpl.xticks(xt, vWidth, fontsize=9) 对y轴重复此步骤。结果是一个图表,其中是每200米的刻度,但整数Km值的数据标签。不管怎样,这些轴的精度是200米,这不是很精确,但对我来说已经足够了。如果我知道如何增加整数刻度的大小,这个脚本会更好…
https://stackoverflow.com/questions/6494232
复制相似问题