如何在长度变化的轴上添加恒定间距的刻度?[蟒蛇]

mmy*_*tti 5 python axis graph matplotlib

为了简化我的问题(它不是那样的,但我更喜欢简单问题的简单答案):

我有几个描绘矩形区域区域的2D地图.我想添加地图轴和刻度以显示此地图上的距离(使用matplotlib,因为旧代码与它一起),但问题是区域大小不同.我想在轴上放置漂亮,清晰的刻度,但地图的宽度和高度可以是任何东西......

试图解释一下我的意思:假设我有一张面积为4.37 km*6.42 km的地区地图.我希望在0,1,2,3和4 km上有x轴刻度:s和0,1,2,3,4,5和6 km上的y轴刻度:s.然而,由于该区域大于4 km*6 km,因此图像和轴距离比4 km和6 km更远.

刻度之间的空间可以是1千米.然而,地图的大小变化很大(比方说,在5-15公里之间),它们是浮动值.我当前的脚本知道区域的大小,并可以将图像缩放到正确的高度/宽度比,但如何告诉它在哪里放置滴答?

可能已经解决了这个问题,但由于我找不到合适的搜索词来解决我的问题,我不得不在这里问一下......

Joe*_*ton 5

只需设置刻度定位器使用的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()
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,无论我们如何缩放或与绘图交互,它总是标有1个单位的刻度. 在此输入图像描述


wer*_*ika 0

这将为您提供 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
Run Code Online (Sandbox Code Playgroud)

对 y 轴重复此操作。

出于好奇:默认情况下您会得到什么样的蜱虫?