簡體   English   中英

使用matplotlib mpld3和LinkedBrush的Json序列化錯誤

[英]Json serialization error using matplotlib mpld3 with LinkedBrush

LinkedBrush http://mpld3.github.io/examples/linked_brush.html上的mpld3d3 matplotlib )示例提供了以下代碼示例:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

import mpld3
from mpld3 import plugins, utils


data = load_iris()
X = data.data
y = data.target

# dither the data for clearer plotting
X += 0.1 * np.random.random(X.shape)

fig, ax = plt.subplots(4, 4, sharex="col", sharey="row", figsize=(8, 8))
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95,
                    hspace=0.1, wspace=0.1)

for i in range(4):
    for j in range(4):
        points = ax[3 - i, j].scatter(X[:, j], X[:, i],
                                      c=y, s=40, alpha=0.6)

# remove tick labels
for axi in ax.flat:
    for axis in [axi.xaxis, axi.yaxis]:
        axis.set_major_formatter(plt.NullFormatter())

# Here we connect the linked brush plugin
plugins.connect(fig, plugins.LinkedBrush(points))

mpld3.show()

雖然公共網頁顯示了鏈接輸出的矩陣,但在本地運行它時會出現json序列化錯誤:

Traceback (most recent call last):
  File "/git/scalatesting/src/main/python/mpld3_linkedbrush.py", line 34, in <module>
    mpld3.show()
  File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 358, in show
    html = fig_to_html(fig, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 251, in fig_to_html
    figure_json=json.dumps(figure_json, cls=NumpyEncoder),
  File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 251, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 138, in default
    return json.JSONEncoder.default(self, obj)
  File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/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

當地的環境是

$pip show mpld3
Name: mpld3
Version: 0.3
Summary: D3 Viewer for Matplotlib
Home-page: http://mpld3.github.com
Author: Jake VanderPlas
Author-email: jakevdp@cs.washington.edu
License: BSD 3-clause
Location: /usr/local/lib/python2.7/site-packages

$python -V
Python 2.7.14

今天安裝了mpld3 是否存在mpld3版本問題? 還有其他建議嗎?

基於從@snakecharmerb評論我從分叉mpld3 ,進入修復建議,並從我在GitHub上新分支PIP安裝。

修復程序在這里: https//github.com/javadba/mpld3/tree/display_fix 它可以通過以下方式安裝:

python -m pip install --user "git+https://github.com/javadba/mpld3@display_fix"

它運行良好: json serialization錯誤消失了,9個圖表之間的聯系正常運行:

在此輸入圖像描述

對我來說, 這里給出的解決方案不起作用。

我有一個networkx圖可視化:

import matplotlib.pyplot as plt
import numpy as np
import mpld3

import networkx as nx
G = nx.path_graph(4)
pos = nx.spring_layout(G)

fig, ax = plt.subplots(subplot_kw=dict(facecolor='#EEEEEE'))
scatter = nx.draw_networkx_nodes(G, pos, ax=ax)
nx.draw_networkx_edges(G, pos, ax=ax)

labels = G.nodes()
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)

mpld3.show()

然后它給出了“JSON not serializable”錯誤。 我找到了上面的鏈接,並嘗試了修復。 修復本質上說如果對象是numpy.ndarray類型,則將其更改為list。

G.nodes的對象類型是networkx.classes.reportviews.NodeView ,而不是numpy.ndarray ; 因此它沒有用。

所以,我修改了文件_display.py增加import networkx並添加以下兩行的default類功能NumpyEncoder ,使其工作:

elif isinstance(obj,networkx.classes.reportviews.NodeView):
    return list(obj)

它現在有效:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM