2017-12-14 10 views
1

Html.I에서 파이썬 플롯을 변환하고 싶습니다. 참조 예를 들어 HTML 페이지로 플롯을 변환했습니다. 아래 코드는 내 코드입니다. 나는 위의 코드를 실행하면Python : TypeError : 배열 ([1.])이 JSON을 직렬화 할 수 없습니다.

import matplotlib as plta 
plta.use('Agg') 
import matplotlib.pyplot as plt 
import numpy as np 
import mpld3 

fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE')) 
N = 100 

scatter = ax.scatter(np.random.normal(size=N), 
        np.random.normal(size=N), 
        c=np.random.random(size=N), 
        s=1000 * np.random.random(size=N), 
        alpha=0.3, 
        cmap=plt.cm.jet) 

ax.grid(color='white', linestyle='solid') 
ax.set_title("Scatter Plot (with tooltips!)", size=20) 

labels = ['point {0}'.format(i + 1) for i in range(N)] 
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels) 
mpld3.plugins.connect(fig, tooltip) 

html_graph = mpld3.fig_to_html(fig) 
with open('plot.html', 'w') as the_file: 
    the_file.write(html_graph) 

는 이제 아래와 같은 오류가 발생합니다 : 도와 function.Please fig_to_html()를 호출하는 동안

/usr/local/lib/python2.7/dist-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead. 
    warnings.warn(message, mplDeprecation, stacklevel=1) 
Traceback (most recent call last): 
    File "d3tool.py", line 24, in <module> 
    html_graph = 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 

오류 라인 (24)에 발생합니다.

+1

이 문제는 현재 mpld3 repo에서 열립니다. 다음은 링크입니다 : https://github.com/mpld3/mpld3/issues/434 –

답변

1

"mpld3/_display.py"파일을 변경하여 문제를 해결했습니다.

부분 아래에 변경하십시오

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) 

자세한 내용에 대한 https://github.com/javadba/mpld3/commit/57ed37dbc4749259b1b46cba8bf28de802972adb을 참조하십시오.