在特定值上放置刻度

2 投票
1 回答
3850 浏览
提问于 2025-04-17 22:53

假设我有一个像下面这样的图表,我想在特定的位置放置Y轴刻度(以及刻度值)。比如说,只在最高值(1.0)和最低值(-1)上放置刻度。

我该怎么做呢?

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

fig, ax = plt.subplots()
plt.plot(t,s)

enter image description here

1 个回答

4

如果你只想在最小值和最大值的位置上放置刻度,可以使用以下方法:

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

fig, ax = plt.subplots()
plt.plot(t,s)

ylims = ax.get_ylim()
ax.set_yticks(ylims)

xlims = ax.get_xlim()
ax.set_xticks(xlims)

plt.show()

ax.get_ylim() 这个函数会返回一个包含最小值和最大值的元组。然后你可以用 ax.set_yticks() 来设置 y 轴的刻度(在这个例子中,我只是用了最小和最大 y 值)。

编辑

你在评论中提到了 LocatorFormatter 对象。我在下面添加了另一个例子,利用这些来:

  1. 设置主要刻度的位置;
  2. 设置次要刻度的位置(它们比较小,但确实存在);
  3. 格式化主要刻度的字符串。

代码中有注释,所以应该能理解,如果你需要更多帮助,随时告诉我。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, LinearLocator, FormatStrFormatter

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

fig, ax = plt.subplots()
plt.plot(t, s)

# Retrieve the limits of the x and y axis.
xlims = ax.get_xlim()
ylims = ax.get_ylim()

# Create two FixedLocator objects. FixedLocator objects take a sequence
# which then is translated into the tick-positions. In this case I have
# simply given the x/y limits as the sequence.
xmajorlocator = FixedLocator(xlims)
ymajorlocator = FixedLocator(ylims)

ax.xaxis.set_major_locator(xmajorlocator)
ax.yaxis.set_major_locator(ymajorlocator)

# Create two LinearLocator objects for use in the minor ticks.
# LinearLocator objects take the number of ticks as an argument
# and automagically calculate the appropriate tick positions.
xminorlocator = LinearLocator(10)
yminorlocator = LinearLocator(10)

ax.xaxis.set_minor_locator(xminorlocator)
ax.yaxis.set_minor_locator(yminorlocator)

# Create two FormatStrFormatters to format the major ticks.
# I've added this simply to complete the example, you can set
# a fmt string using Python syntax to control how your ticks
# look. In this example I've formatted them as floats with
# 3 and 2 decimal places respectively.
xmajorformatter = FormatStrFormatter('%.3f')
ymajorformatter = FormatStrFormatter('%.2f')

ax.xaxis.set_major_formatter(xmajorformatter)
ax.yaxis.set_major_formatter(ymajorformatter)

plt.show()

我还附上了更新后的图表,里面有新的刻度格式,我会把旧的去掉以节省空间。

示例图

撰写回答