绘制极坐标散点图,将图像作为标记,matplotlib:无法将NaN转换为整数

时间:2016-10-07 15:19:45

标签: python matplotlib

给定一个pandas数据帧,我有一些代码可以创建一个散点图并在每个点放置一个指定的png:

import matplotlib.pyplot as plt
from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox

threshold = 0.05
fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot(111)
bound = 0.2
ax.set_xlim([-bound,bound])
ax.set_ylim([-bound,0.25])
ax.set_axis_bgcolor('white')

for index, row in high_low.iterrows():
    x = row['row1']
    y = row['row2']
    if abs(x) > threshold or abs(y) > threshold:
        im = plt.imread('/path/to/my/image_' + str(index) + '.png')
        bb = Bbox.from_bounds(x,y,.01,.01)  
        bb2 = TransformedBbox(bb,ax.transData)
        bbox_image = BboxImage(bb2,
                            norm = None,
                            origin=None,
                            clip_on=False,
                          alpha=0.75)

        bbox_image.set_data(im)
        ax.add_artist(bbox_image)

ax.grid(True, color="black", linestyle="--")
plt.savefig("myfig.svg", dpi=300, format='svg')

我想将此图更改为极坐标,因此我添加了以下函数

def cart2pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

并将我的代码更改为:

ax = fig.add_subplot(111, polar=True) # <- CHANGE HERE
ax.set_axis_bgcolor('white')
for index, row in high_low.iterrows():
    x = row['row1']
    y = row['row2']
    if abs(x) > threshold or abs(y) > threshold:
        rho, phi = cart2pol(x, y) # <- CHANGE HERE
        im = plt.imread('/path/to/my/image_' + str(index) + '.png')
        bb = Bbox.from_bounds(rho,phi,.01,.01)   # <- CHANGE HERE
        bb2 = TransformedBbox(bb,ax.transData)
        bbox_image = BboxImage(bb2,
                            norm = None,
                            origin=None,
                            clip_on=False,
                          alpha=0.75)

        bbox_image.set_data(im)
        ax.add_artist(bbox_image)
ax.grid(True, color="black", linestyle="--")
plt.savefig("myfigPolar.pdf", dpi=300, format='pdf')

循环运行:

...
<matplotlib.image.BboxImage object at 0x7f6b805fb390>
<matplotlib.image.BboxImage object at 0x7f6b805fb6d0>
<matplotlib.image.BboxImage object at 0x7f6b805fba10>
...

但是在绘图时出现以下错误:

>>> plt.savefig("myfigPolar.pdf", dpi=300, format='pdf')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 561, in savefig
    return fig.savefig(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1421, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 2220, in print_figure
    **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1952, in print_pdf
    return pdf.print_pdf(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_pdf.py", line 2352, in print_pdf
    self.figure.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/figure.py", line 1034, 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 2086, 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/image.py", line 1182, in draw
    im = self.make_image(renderer, image_mag)
  File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1172, in make_image
    im.resize(int(widthDisplay), int(heightDisplay),
ValueError: cannot convert float NaN to integer

不确定我做错了什么。 rhophi都不是Nan,也不是超小浮点数(我已经看到在其他Stackoverflow答案中导致此错误)。

修改:回复要求plt.show()

的评论
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 276, in resize
    self.show()
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 348, in draw
    FigureCanvasAgg.draw(self)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 451, 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 1034, 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 2086, 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/image.py", line 1182, in draw
    im = self.make_image(renderer, image_mag)
  File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1172, in make_image
    im.resize(int(widthDisplay), int(heightDisplay),
ValueError: cannot convert float NaN to integer

rhophi

的最小值和最大值
>>> min(rho), max(rho)
(0.10336371748137782, 0.22005286472537541)
>>> min(phi), max(phi)
(-2.9088677009635697, 1.3618299263576035)

1 个答案:

答案 0 :(得分:1)

显然,您需要将正角度传递给Bbox。这应该有效:

def cart2pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    if phi < 0:
        phi += 2 * np.pi
    return(rho, phi)