matplotlib文本(和figtext)错误
我想在一个MDS解决方案中绘制文本值,而不是符号,但使用matplotlib.pyplot
时遇到了我不理解的错误。我已经更新了ipython和matplotlib,以确保这不是一个旧版本的问题,但我在这里(或通过谷歌)找不到任何类似问题的答案或报告。
举个例子,在调用ipython --pylab
后,如果我输入:
x = random.rand(4)
y = random.rand(4)
s = [str(i) for i in arange(4)+1]
text(x,y,s)
我就会收到这个错误:
Traceback (most recent call last):
File "//anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in
draw_wrapper draw(artist, renderer, *args, **kwargs)
File "//anaconda/lib/python2.7/site-packages/matplotlib/figure.py", line 1034, in draw
func(*args)
File "//anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in
draw_wrapper draw(artist, renderer, *args, **kwargs)
File "//anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 2086, in draw
a.draw(renderer)
File "//anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in
draw_wrapper draw(artist, renderer, *args, **kwargs)
File "//anaconda/lib/python2.7/site-packages/matplotlib/text.py", line 547, in draw
bbox, info, descent = self._get_layout(renderer)
File "//anaconda/lib/python2.7/site-packages/matplotlib/text.py", line 287, in
_get_layout key = self.get_prop_tup()
File "//anaconda/lib/python2.7/site-packages/matplotlib/text.py", line 696, in
get_prop_tup x, y = self.get_position()
File "//anaconda/lib/python2.7/site-packages/matplotlib/text.py", line 684, in
get_position x = float(self.convert_xunits(self._x))
TypeError: only length-1 arrays can be converted to Python scalars
如果我尝试用标量而不是向量/列表来调用文本(例如,text(x[0],y[0],s[0])
,或者text
函数的任何参数变体),也会出现同样的错误。情况是一样的:
- 使用
figtext
时, - 如果我手动
import matplotlib.pyplot as plt
并调用plt.text
, - 如果我明确创建图形和子图对象,或者先调用
scatter(x,y)
。
另外,一旦出现这个问题,如果我手动调整图形大小,错误信息会再次出现。可能相关的是,图形的更改不会自动更新,而是只有在我在另一个子图中绘图或手动调整图形大小后才会更新。但我偏题了。
我在Mac上安装了更新的Anaconda(使用Mavericks),而且如上所述,我正在使用iPython。
1 个回答
4
plt.text
这个函数需要你给它一个单独的 x 坐标、y 坐标和一个字符串,而不是一堆数据。你可以查看这个链接了解更多信息:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text。
你可以用一个循环来解决这个问题。
比如说:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.rand(2,4)
s = [str(i) for i in np.arange(1, 5)]
fig, ax = plt.subplots()
text = [ax.text(*item) for item in zip(x, y, s)]
plt.show()