python - After saving a plotly figure to html file, can you re-read it later as a figure?
问题描述
I'd like to edit the data, probably adding more traces to the graph. I've found a way to display the html file as a graph, but not to edit it.
from IPython.display import HTML
HTML(filename='file_name.html')
解决方案
通常Plotly JSON应该用于图表的(反)序列化(例如figure.write_json
和plotly.read_json
)。但是,如果您只有图表的 HTML 表示形式,则会将相同的 Plotly JSON 提供给plotly.js
那里,并且可以将其提取出来。
仅用于演示。plotly==5.1.0
用过的。
import json
import re
import plotly.express
def write():
fig = plotly.express.bar(y=[0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
fig.write_html('plot.html', full_html=True)
fig.write_json('plot.json')
def read_from_json():
return plotly.io.read_json('plot.json')
def read_from_html():
with open('plot.html') as f:
html = f.read()
call_arg_str = re.findall(r'Plotly\.newPlot\((.*)\)', html[-2**16:])[0]
call_args = json.loads(f'[{call_arg_str}]')
plotly_json = {'data': call_args[1], 'layout': call_args[2]}
return plotly.io.from_json(json.dumps(plotly_json))
if __name__ == '__main__':
write()
read_from_json()
read_from_html()
推荐阅读
- android - How to hide android's bottom navigation bar in flutter
- openebs - 我可以从我的节点(OpenEBS)运行 mayactl 吗?
- database - Drupal 8 中的内容类型是否与数据库中的表相同?
- ios - 在动画的 UIView 上获取点的颜色
- python - 模糊图像的特定部分
- angular - angular 6 根据类型动态显示模板
- java - 如何获得某个地区/国家/地区的第一天
- html - 如何自动打开相机
- java - 用于 log4j2 的 Slack 附加程序
- android - 如何获得最后两个节点?