更改 x 或 y 轴上的刻度频率

新手上路,请多包涵

我正在尝试修复 python 如何绘制我的数据。说:

 x = [0,5,9,10,15]
y = [0,1,2,3,4]

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

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

原文由 Dax Feliz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 577
2 个回答

您可以使用 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 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 已经设置的限制。

 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()

原文由 unutbu 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一种方法是设置轴定位器:

 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()

原文由 robochat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题