You could explicitly set where you want to tick marks with plt.xticks
:
(您可以使用plt.xticks
显式设置要在标记上plt.xticks
:)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
For example,
(例如,)
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
was used rather than Python's range
function just in case min(x)
and max(x)
are floats instead of ints.)
((以防min(x)
和max(x)
是浮点数而不是整数的情况,使用了np.arange
而不是Python的range
函数。))
The plt.plot
(or ax.plot
) function will automatically set default x
and y
limits.
(plt.plot
(或ax.plot
)函数将自动设置默认的x
和y
限制。)
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. (如果您希望保留这些限制,而只是更改刻度线的步长,则可以使用ax.get_xlim()
来发现Matplotlib已设置的限制。)
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()