使用 Plotly 绘制可迭代类

问题描述 投票:0回答:1

我在绘制 Python 中的一些可迭代类时遇到一些问题。这个想法是使用plotly来绘制从类的迭代器获得的线。这是该类的一个示例:

class example_class:
    ## Constructor
    def __init__(self, n):
        self.int_part = np.random.randint(0, 1023, size=n, dtype=np.uint16)
        self.dec_part = np.random.randint(0, 127, size=n, dtype=np.uint16)
        self.current = 0
        self.n = n

    ## Iterator
    def __iter__(self):
        return self

    ## Next element during the iteration
    def __next__(self):
        if self.current < self.n:
            v = self.int_part[self.current] + self.dec_part[self.current]/100
            self.current += 1
            return v
        raise StopIteration

    ## Length
    def __len__(self):
        return self.n

仅绘制该类的一个实例是没有问题的。例如,以下代码生成正确的线图

import numpy as np
import plotly.express as px

C = example_class(100)
fig = px.line(C)
fig.show()

但是如果我想添加更多行,就像这样

import numpy as np
import plotly.express as px

C = example_class(100)
D = example_class(100)
E = example_class(100)

fig = px.line(x=np.arange(0,100), y=[D,E])
fig.show()

我收到以下错误

Traceback (most recent call last):
File "test.py", line 34, in <module>
    fig.show()
  File "/home/jose/anaconda3/lib/python3.7/site-packages/plotly/basedatatypes.py", line 3409, in show
    return pio.show(self, *args, **kwargs)
  File "/home/jose/anaconda3/lib/python3.7/site-packages/plotly/io/_renderers.py", line 403, in show
    renderers._perform_external_rendering(fig_dict, renderers_string=renderer, **kwargs)
  File "/home/jose/anaconda3/lib/python3.7/site-packages/plotly/io/_renderers.py", line 340, in _perform_external_rendering
    renderer.render(fig_dict)
  File "/home/jose/anaconda3/lib/python3.7/site-packages/plotly/io/_base_renderers.py", line 759, in render
    validate=False,
  File "/home/jose/anaconda3/lib/python3.7/site-packages/plotly/io/_html.py", line 144, in to_html
    jdata = to_json_plotly(fig_dict.get("data", []))
  File "/home/jose/anaconda3/lib/python3.7/site-packages/plotly/io/_json.py", line 143, in to_json_plotly
    json.dumps(plotly_object, cls=PlotlyJSONEncoder, **opts), _swap_json
  File "/home/jose/anaconda3/lib/python3.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/home/jose/anaconda3/lib/python3.7/site-packages/_plotly_utils/utils.py", line 59, in encode
    encoded_o = super(PlotlyJSONEncoder, self).encode(o)
  File "/home/jose/anaconda3/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/home/jose/anaconda3/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/home/jose/anaconda3/lib/python3.7/site-packages/_plotly_utils/utils.py", line 136, in default
    return _json.JSONEncoder.default(self, obj)
  File "/home/jose/anaconda3/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type example_class is not JSON serializable

我尝试了很多替代方案但没有成功。

有人知道如何解决吗?

谢谢! 何塞

python plotly iterable
1个回答
0
投票

当构建不同的图形时(特别是

line
plotly
执行许多不同的检查,其中包括强制转换、清理,以及在生成器/迭代器的情况下,通过构造新索引(或-称为 placement) - 在这种情况下它们之间的尺寸可能会有所不同。
要处理/自动化索引准备(对于
x
轴),您可以传递
pd.DataFrame
并为
y
轴指定所需的 df 列:

import numpy as np
import plotly.express as px

fig = px.line(pd.DataFrame({'D': example_class(100), 
                            'E': example_class(100)}), y=['D', 'E'])
fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.