【问题标题】:mpld3 3D scatter plotmpld3 3D散点图
【发布时间】:2017-02-11 08:08:34
【问题描述】:

我正在探索 mpld3 库,但不知道如何创建 3D 散点图。 使用 Matplotlib 我会这样做:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter([1],[5],[7])
plt.show()

同样,我尝试使用 mpld3(在 Jupyter 笔记本中): 将 matplotlib.pyplot 导入为 plt 从 mpl_toolkits.mplot3d 导入 Axes3D 导入mpld3

mpld3.enable_notebook()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter([1],[5],[7])
mpld3.display(fig) 

我得到了错误

TypeError: array([ 0.94,  1.06]) is not JSON serializable

有什么想法吗?

这是完整的错误日志:

Traceback (most recent call last) <ipython-input-26-54fc4a65da87> in <module>()
      6 N = 50
      7 ax.scatter([1],[5],[7])
----> 8 mpld3.display(fig)

/usr/local/lib/python2.7/dist-packages/mpld3/_display.pyc in display(fig, closefig, local, **kwargs)
    288     if closefig:
    289         plt.close(fig)
--> 290     return HTML(fig_to_html(fig, **kwargs))
    291 
    292 

/usr/local/lib/python2.7/dist-packages/mpld3/_display.pyc in fig_to_html(fig, d3_url, mpld3_url, no_extras, template_type, figid, use_http, **kwargs)
    234                            d3_url=d3_url,
    235                            mpld3_url=mpld3_url,
--> 236                            figure_json=json.dumps(figure_json),
    237                            extra_css=extra_css,
    238                            extra_js=extra_js)

/usr/lib/python2.7/json/__init__.pyc in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, sort_keys, **kw)
    241         cls is None and indent is None and separators is None and
    242         encoding == 'utf-8' and default is None and not sort_keys and not kw):
--> 243         return _default_encoder.encode(obj)
    244     if cls is None:
    245         cls = JSONEncoder

/usr/lib/python2.7/json/encoder.pyc in encode(self, o)
    205         # exceptions aren't as detailed.  The list call should be roughly
    206         # equivalent to the PySequence_Fast that ''.join() would do.
--> 207         chunks = self.iterencode(o, _one_shot=True)
    208         if not isinstance(chunks, (list, tuple)):
    209             chunks = list(chunks)

/usr/lib/python2.7/json/encoder.pyc in iterencode(self, o, _one_shot)
    268                 self.key_separator, self.item_separator, self.sort_keys,
    269                 self.skipkeys, _one_shot)
--> 270         return _iterencode(o, 0)
    271 
    272 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

/usr/lib/python2.7/json/encoder.pyc in default(self, o)
    182 
    183         """
--> 184         raise TypeError(repr(o) + " is not JSON serializable")
    185 
    186     def encode(self, o):

TypeError: array([ 0.94,  1.06]) is not JSON serializable

【问题讨论】:

  • 函数display调用另一个函数figure_to_html。后者需要将图形的表示保存到文件中,然后使用 JSON 文件。问题是数组不是 JSON 可序列化的,如消息中所示。
  • 你能给我们看看日志吗?
  • @MMF 在这种情况下你有一个可行的解决方案吗? [ 0.94, 1.06] 数组首先来自哪里?...
  • 是的,这就是我想要理解的。如果您能提供对我有很大帮助的错误日志!
  • 我深入研究了源代码,但不幸的是我无法发现错误。 renderer 对象似乎有一个名为 finished_figures 的属性,错误可能来自其使用类数组对象进行的初始化。但是他们将数组转换为代码中的列表,所以我不知道为什么会引发此错误:/也许是包含错误的旧版本?你有没有想过更新库?

标签: python matplotlib mpld3


【解决方案1】:

如前所述,mpld3 不支持 3D 图形,但请查看下面的包,它们也旨在通过 python 和 进行可视化plotly 将 matplotlib 图形转换为他们的图形,mpld3 也有。

【讨论】:

    【解决方案2】:

    很遗憾,mpld3 目前不支持 3D 绘图。它仅支持 2D 绘图。检查以下链接:

    【讨论】:

      【解决方案3】:

      对不起,这不是一个完整的答案,而是一个很长的评论......

      我可以通过如下编辑 mpld3._display.py 来消除错误:

      class NumpyEncoder(json.JSONEncoder):
          """ Special json encoder for numpy types """
      
          def default(self, obj):
              try: 
                  obj=obj.tolist()
                  return json.JSONEncoder.encode(self, obj)
              except AttributeError:
                  pass
              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)
      
              return json.JSONEncoder.default(self, obj)
      

      但是它会在笔记本中生成一个带有错误消息的空图:

      Javascript error adding output!
      TypeError: t.map is not a function
      See your browser Javascript console for more details.
      

      看起来 mpld3 不是为支持 3D 而设计的……

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 1970-01-01
        • 2020-04-17
        相关资源
        最近更新 更多