title: mpld3._display.NumpyEncoder报错
date: 2019-08-12 20:16:18
tags: [matplotlib, mpld3, _display, error]
categories: programming/python/mpld3
https://www.exobrain.online/2019/08/12/mpld3-display-NumpyEncoder报错/
在使用mpld3.display.NumpyEncoder过程中报错
Traceback (most recent call last):
File "ttt.py", line 55, in
htmlfil.write(mpld3.fig_to_html(fig))
File "/usr/local/lib/python2.7/dist-packages/mpld3/_display.py", line 251, in fig_to_html
figure_json=json.dumps(figure_json, cls=NumpyEncoder),
File "/usr/lib/python2.7/json/init.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/local/lib/python2.7/dist-packages/mpld3/_display.py", line 138, in default
return json.JSONEncoder.default(self, obj)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: array([ 1.]) is not JSON serializable
可以在mpld3._display()中修改NumpyEncoder类
使用anaconda3用户的包在下面这个位置
/Users/用户名/anaconda3/envs/虚拟环境名/lib/python3.5/site-packages/mpld3
class NumpyEncoder(json.JSONEncoder):
""" Special json encoder for numpy types """
def default(self, obj):
if isinstance(obj, (numpy.int_, numpy.intc, numpy.intp, numpy.int8,
numpy.int16, numpy.int32, numpy.int64, numpy.uint8,
numpy.uint16,numpy.uint32, numpy.uint64)):
return int(obj)
elif isinstance(obj, (numpy.float_, numpy.float16, numpy.float32,
numpy.float64)):
return float(obj)
elif isinstance(obj,(numpy.ndarray,)): #### This is the fix
return obj.tolist()
return json.JSONEncoder.default(self, obj)
- 如果找不到_display路径
可以通过envs/环境变量/conda-meta/mpld3-0.3-py35_0.json文件找到安装路径找到"paths_data"
从而找到
{
“_path”: “lib/python3.5/site-packages/mpld3/pycache/_display.cpython-35.pyc”,
“path_type”: “hardlink”,
“sha256”: “3cd28fc146c93bbb8e211212d4308494e210ccb56ece4976bc60bfef00cc1a27”,
“sha256_in_prefix”: “3cd28fc146c93bbb8e211212d4308494e210ccb56ece4976bc60bfef00cc1a27”,
“size_in_bytes”: 16226
},
url:
https://github.com/mpld3/mpld3/issues/434
https://www.exobrain.online/2019/08/12/mpld3-display-NumpyEncoder报错/