改变“滴答频率"在 matplotlib 的 x 或 y 轴上

2022-01-30 00:00:00 python matplotlib plot axes xticks

问题描述

我正在尝试修复 python 如何绘制我的数据.

I am trying to fix how python plots my data.

x = [0,5,9,10,15]

y = [0,1,2,3,4]

那么我会这样做:

matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()

并且 x 轴的刻度以 5 的间隔绘制.有没有办法让它显示 1 的间隔?

and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?


解决方案

您可以使用 plt.xticks 显式设置要标记的位置:

You could explicitly set where you want to tick marks with plt.xticks:

plt.xticks(np.arange(min(x), max(x)+1, 1.0))

<小时>

例如,

import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()

<小时>使用

(np.arange 而不是 Python 的 range 函数,以防 min(x)max(x) 是浮点数而不是整数.)


(np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.)

plt.plot(或ax.plot)函数将自动设置默认xy限制.如果您希望保持这些限制,并且只是更改刻度线的步长,那么您可以使用 ax.get_xlim() 来发现 Matplotlib 已经设置的限制.

The plt.plot (or ax.plot) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set.

start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))

默认的刻度格式化程序应该可以将刻度值四舍五入到合理的有效数字位数.但是,如果您希望对格式有更多的控制,您可以定义自己的格式化程序.例如,

The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,

ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))

这是一个可运行的示例:

Here's a runnable example:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()

相关文章