溫馨提示×

Plotly怎么將圖表轉(zhuǎn)換為HTML字符串

小億
107
2024-05-17 15:16:15
欄目: 編程語言

要將Plotly圖表轉(zhuǎn)換為HTML字符串,可以使用plotly.offline.plot函數(shù)生成一個HTML文件,然后將文件內(nèi)容讀取為字符串。具體步驟如下:

  1. 導(dǎo)入plotly庫和offline模塊:
import plotly
from plotly.offline import plot
  1. 創(chuàng)建一個Plotly圖表對象,例如一個散點圖:
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)
  1. 使用plotly.offline.plot函數(shù)將圖表保存為HTML文件:
plot(fig, filename='scatter_plot.html')
  1. 讀取HTML文件內(nèi)容為字符串:
with open('scatter_plot.html', 'r') as file:
    html_string = file.read()

現(xiàn)在,html_string變量中包含了將Plotly圖表轉(zhuǎn)換為HTML字符串的內(nèi)容。

0