要将Plotly图表转换为HTML字符串,可以使用plotly.offline.plot
函数生成一个HTML文件,然后将文件内容读取为字符串。具体步骤如下:
import plotly
from plotly.offline import plot
import plotly.graph_objs as go
data = [
go.Scatter(
x=[1, 2, 3],
y=[1, 2, 3],
mode='markers'
)
]
layout = go.Layout(
title='Plotly Scatter Plot'
)
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot
函数将图表保存为HTML文件:plot(fig, filename='scatter_plot.html')
with open('scatter_plot.html', 'r') as file:
html_string = file.read()
现在,html_string
变量中包含了将Plotly图表转换为HTML字符串的内容。