我在Seaborn图书馆遇到一个奇怪的问题。当生成具有从非常低到非常高的值的数据的条形图时,例如:
job duration type
0 1 83066.639344 A
1 2 820.700000 B
它失败并显示:
ValueError: cannot convert float NaN to integer
这看起来像是matplotlib中的错误,并且是"pyplot.savefig fails with ValueError: cannot convert float NaN to integer"的重复项。后者尚未修复。有解决方法吗?
这是重现此问题的最小工作示例:
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
d = {'job': [1, 2]),
'duration': [83066.639344, 820.700000],
'type': ['A', 'B']}
df = pd.DataFrame(d)
plot = sns.catplot(x="duration", y="job", data=df, hue='type',
color="b", kind="bar", height=3, aspect=4)
ax = plot.axes.flat[0]
for p in plt.gca().patches:
ax.text(p.get_width(),
p.get_y() + p.get_height() / 2,
p.get_width())
plot.savefig("barplot.png")
一些观察:
hue='type'
)时,不会发生此问题。这是完整的堆栈跟踪:
posx and posy should be finite values
posx and posy should be finite values
/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/numpy/core/fromnumeric.py:83: RuntimeWarning: invalid value encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
posx and posy should be finite values
posx and posy should be finite values
posx and posy should be finite values
Traceback (most recent call last):
File "/Users/dzieciou/projects/example/gocd/reproduce.py", line 31, in <module>
plot.savefig("barplot.png")
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/seaborn/axisgrid.py", line 37, in savefig
self.fig.savefig(*args, **kwargs)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/figure.py", line 2094, in savefig
self.canvas.print_figure(fname, **kwargs)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/backend_bases.py", line 2075, in print_figure
**kwargs)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 510, in print_png
FigureCanvasAgg.draw(self)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 402, in draw
self.figure.draw(self.renderer)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/artist.py", line 50, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/figure.py", line 1649, in draw
renderer, self, artists, self.suppressComposite)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/image.py", line 138, in _draw_list_compositing_images
a.draw(renderer)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/artist.py", line 50, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 2610, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/image.py", line 138, in _draw_list_compositing_images
a.draw(renderer)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/artist.py", line 50, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/axis.py", line 1185, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/axis.py", line 1023, in _update_ticks
tick_tups = list(self.iter_ticks()) # iter_ticks calls the locator
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/axis.py", line 967, in iter_ticks
majorLocs = self.major.locator()
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/ticker.py", line 1985, in __call__
return self.tick_values(vmin, vmax)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/ticker.py", line 1993, in tick_values
locs = self._raw_ticks(vmin, vmax)
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/ticker.py", line 1932, in _raw_ticks
nbins = np.clip(self.axis.get_tick_space(),
File "/Users/dzieciou/virtualenvs/seaborn/lib/python3.7/site-packages/matplotlib/axis.py", line 2543, in get_tick_space
return int(np.floor(length / size))
ValueError: cannot convert float NaN to integer
答案 0 :(得分:1)
请注意,这既不是真正的错误,也与链接的错误无关,该错误确实已修复。
有人可能会争辩说,尽管在nan
坐标处绘制文本时应该有更好的错误消息。
在查看错误之前,似乎您的代码中还有另一个问题,即您将文本的x坐标设置为条形的宽度。它们通常是无关的,您可能打算改用p.get_x()
。
现在有两个选择:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
d = {'job': list(range(1, 3)),
'duration': [83066.639344, 820.700000],
'type': ['A', 'B']}
df = pd.DataFrame(d)
plot = sns.catplot(x="duration", y="job", data=df, hue='type',
color="b", kind="bar", height=3, aspect=4)
ax = plot.axes.flat[0]
for p in plt.gca().patches:
height = np.nan_to_num(p.get_height(), 0)
ax.text(p.get_x(), p.get_y() + height/2., "My text")
plot.savefig("barplot.png")
plt.show()
bbox_inches="tight"
。如果您想保持代码原样,可以通过不设置seaborn的bbox_inches="tight"
中的savefig
选项来解决此问题。
plot.savefig("barplot.png", bbox_inches=None)
或使用matplotlib的savefig选项
plot.fig.savefig("barplot.png")