简体   繁体   English

在python中使用matplotlib设置刻度位置时出错

[英]Error setting tick positions with matplotlib in python

I'm trying to set tick mark positions in matplotlib. 我正在尝试在matplotlib中设置刻度标记位置。 I get errors when running the following minimal example: 运行以下最小示例时出现错误:

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

The error lies with the two lines that set the x- and y-axis tick marks. 错误在于设置x轴和y轴刻度线的两条线。 If I use NullFormatter() instead, or omit these lines entirely, the code runs fine and produces the expected plot. 如果我改为使用NullFormatter(),或者完全省略这些行,代码运行正常并产生预期的图。 The above code, however, returns the following error: 但是,上面的代码返回以下错误:

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'

I've tried googling this error, but I can't find anyone else who has a similar problem. 我试过谷歌搜索这个错误,但我找不到其他有类似问题的人。 Any ideas as to why the use of locators is yielding errors? 关于使用定位器为什么会产生错误的任何想法?

MultipleLocator is a locator, not a formatter. MultipleLocator是一个定位器,而不是格式化程序。 You want to use 你想用

ax.xaxis.set_major_locator(MultipleLocator(1.))
ax.yaxis.set_major_locator(MultipleLocator(1.))

This works for me (doesn't look too pretty using 1, but it works). 这适合我(使用1看起来不太漂亮,但它有效)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM