我正在try 修复python如何绘制数据.
说
x = [0,5,9,10,15]
和
y = [0,1,2,3,4]
那我就会这么做:
matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()
和 the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
我正在try 修复python如何绘制数据.
说
x = [0,5,9,10,15]
和
y = [0,1,2,3,4]
那我就会这么做:
matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()
和 the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
您可以使用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)
是浮点型而不是整型的情况下.)
plt.plot
(或ax.plot
)功能将自动设置默认的x
和y
限制.如果希望保持这些限制,只需更改记号的步长,那么可以使用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. 例如
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
下面是一个可运行的示例:
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()