更改“滴答频率"在 matplotlib 的 x 或 y 轴上? [英] Changing the "tick frequency" on x or y axis in matplotlib?
问题描述
我正在尝试修复 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
)函数会自动设置默认的x
和y
限制.如果您希望保留这些限制,而只是更改刻度线的步长,那么您可以使用 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()
这篇关于更改“滴答频率"在 matplotlib 的 x 或 y 轴上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!