我在一些可迭代类的绘制上遇到了一些问题.其思想是使用情节来绘制从类的迭代器获得的线条.以下是该类的一个示例:

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()

enter image description here

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

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

我try 了许多替代方案,但都没有成功.

有谁知道怎么解决这个问题吗?

埃米利亚诺! 何塞

推荐答案

当构建不同的图形(特别是line)时,plotly执行许多不同的判断,其中包括强制转换、清理,以及在生成器/迭代器的情况下,通过构建新的索引(或所谓的placement)来实现这些判断-在这种情况下,它们之间的大小可能会不同.
要处理/自动化索引准备(针对x轴),可以传递pd.DataFrame并为y轴指定所需的df列:

import numpy as np
import pandas as pd
import plotly.express as px

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

enter image description here

Python相关问答推荐

使用mySQL的SQlalchemy过滤重叠时间段

Polars LazyFrame在收集后未返回指定的模式顺序

如何使用Python将工作表从一个Excel工作簿复制粘贴到另一个工作簿?

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

如何在虚拟Python环境中运行Python程序?

通过pandas向每个非空单元格添加子字符串

numpy卷积与有效

如何在Raspberry Pi上检测USB并使用Python访问它?

如何将多进程池声明为变量并将其导入到另一个Python文件

将JSON对象转换为Dataframe

如何在Python中找到线性依赖mod 2

Django admin Csrf令牌未设置

使用BeautifulSoup抓取所有链接

幂集,其中每个元素可以是正或负""""

在Python中使用yaml渲染(多行字符串)

并行编程:同步进程

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

没有内置pip模块的Python3.11--S在做什么?

如何在python tkinter中绑定键盘上的另一个回车?

Pandas 删除只有一种类型的值的行,重复或不重复