我正在尝试在matplotlib中设置刻度标记位置。运行以下最小示例时出现错误:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
x = 10.*np.random.randn(1000)
y = 10.*np.random.randn(1000)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x, y)
ax.xaxis.set_major_formatter(MultipleLocator(1.))
ax.yaxis.set_major_formatter(MultipleLocator(1.))
plt.show()
错误在于设置x轴和y轴刻度线的两条线。如果我改为使用NullFormatter(),或者完全省略这些行,代码运行正常并产生预期的图。但是,上面的代码会返回以下错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 245, in resize
self.show()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 248, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 394, in draw
self.figure.draw(self.renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 798, in draw
func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 1946, in draw
a.draw(renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 971, in draw
tick_tups = [ t for t in self.iter_ticks()]
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 906, in iter_ticks
self.major.formatter.set_locs(majorLocs)
AttributeError: MultipleLocator instance has no attribute 'set_locs'
我试过谷歌搜索这个错误,但我找不到其他有类似问题的人。关于使用定位器为什么会产生错误的任何想法?
答案 0 :(得分:8)
MultipleLocator是一个定位器,而不是格式化程序。你想用
ax.xaxis.set_major_locator(MultipleLocator(1.))
ax.yaxis.set_major_locator(MultipleLocator(1.))
这适合我(使用1看起来不太漂亮,但它有效)。