我正在尝试修复python绘制数据的方式。
说
x = [0,5,9,10,15]和
y = [0,1,2,3,4]然后我会这样做:
matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()X轴的刻度是以5为间隔绘制的,有没有办法让它显示间隔为1呢?
发布于 2012-09-27 03:24:09
您可以使用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))默认的刻度格式化程序应该很好地将刻度值四舍五入为合理的有效位数。但是,如果您希望对格式有更多的控制,您可以定义自己的格式化程序。例如,
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()发布于 2013-11-14 16:38:42
另一种方法是设置轴定位器:
import matplotlib.ticker as plticker
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)根据您的需要,有几种不同类型的定位器。
下面是一个完整的示例:
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.show()发布于 2016-03-26 07:24:38
我喜欢这个解决方案(来自Matplotlib Plotting Cookbook):
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
tick_spacing = 1
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()这个解决方案让您可以通过给ticker.MultipleLocater()的数字显式地控制刻度间距,允许自动确定限制,并且以后很容易阅读。
https://stackoverflow.com/questions/12608788
复制相似问题