python - 在特定值上打勾

标签 python matplotlib

假设我有一个如下图所示的绘图,并且我想在特定位置放置 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

最佳答案

要仅在可以使用的最小值和最大值上打勾:

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 值)。

编辑

您提到了 Locator 的使用和 Formatter您评论中的对象。我在下面提供了另一个示例,该示例利用这些来:

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

我还包含了具有新刻度格式的更新图表,我将删除旧图表以节省空间。

Example plot

关于python - 在特定值上打勾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491502/

相关文章:

python - 使用 matplotlib 时,LaTeX 方程不会在 google Colaboratory 中呈现

python 和 Pandas : Strange behavior when Pandas plot histogram to a specific ax

python - 使用 imshow 和 twiny : cannot set xlim

python - 无法修改方法外部的变量

python - Django 错误页面不显示语法错误

python - 如何在x轴上以正确的频率绘制信号的FFT?

python - 将颜色图与 matplotlib 循环器一起使用

python - 使用 NumPy 进行 LMS 批量梯度下降

python - Pandas ;棘手的数据透视表

python - 设置 Beeware : I cannot create my JAR support file within my activated venv