要將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字符串的內容。