簡體   English   中英

將多個圖保存到單個 html 中

[英]Plotly saving multiple plots into a single html

我最近發現了 plotly 並發現它非常適合繪圖,現在我有一個問題,我想將多個繪圖保存到一個 html 中,請問該怎么做?

*我想保存多個圖,即圖,圖1,圖2等,而不是一個有多個圖的子圖,因為我發現子圖中的圖太小了。

在 Plotly API 中有一個to_html函數,它返回圖形的 HTML。 此外,您可以設置選項 param full_html=False這將為您提供僅包含數字的 DIV。

您可以通過附加包含圖形的 DIV 將多個圖形寫入一個 HTML:

with open('p_graph.html', 'a') as f:
    f.write(fig1.to_html(full_html=False, include_plotlyjs='cdn'))
    f.write(fig2.to_html(full_html=False, include_plotlyjs='cdn'))
    f.write(fig3.to_html(full_html=False, include_plotlyjs='cdn'))

https://plot.ly/python-api-reference/generated/plotly.io.to_html.html

您還可以使用 Beautiful Soup 進行 DOM 操作,並將 DIV 准確插入 HTML 中您需要的位置。

https://beautiful-soup-4.readthedocs.io/en/latest/#append

這是一個看起來不錯的示例:

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
import numpy as np
import plotly

y1 = np.random.randn(200) - 1
y2 = np.random.randn(200)
y3 = np.random.randn(200) + 1
x = np.linspace(0, 1, 200)

colors = ['#3f3f3f', '#00bfff', '#ff7f00']

fig = make_subplots(
    rows=3, cols=2,



    column_widths=[0.55, 0.45],
    


    row_heights=[1., 1., 1.],
    specs=[[{"type": "scatter"}, {"type": "xy"}],
           [{"type": "scatter"}, {"type": "xy", "rowspan": 2}],
           [{"type": "scatter"},            None           ]])


fig.add_trace(
    go.Scatter(x = x, 
                y = y1,
                hoverinfo = 'x+y',
                mode='lines',
                line=dict(color='#3f3f3f',
                width=1),
                showlegend=False,
                ),
    row=1, col=1
)

fig.add_trace(
    go.Scatter(x = x, 
                y = y2,
                hoverinfo = 'x+y',
                mode='lines',
                line=dict(color='#00bfff',
                width=1),
                showlegend=False,
                ),
    row=2, col=1
)

fig.add_trace(
    go.Scatter(x = x, 
                y = y3,
                hoverinfo = 'x+y',
                mode='lines',
                line=dict(color='#ff7f00',
                width=1),
                showlegend=False,
                ),
    row=3, col=1
)


boxfig= go.Figure(data=[go.Box(x=y1, showlegend=False, notched=True, marker_color="#3f3f3f", name='3'),
                        go.Box(x=y2, showlegend=False, notched=True, marker_color="#00bfff", name='2'),
                        go.Box(x=y3, showlegend=False, notched=True, marker_color="#ff7f00", name='1')])

for k in range(len(boxfig.data)):
     fig.add_trace(boxfig.data[k], row=1, col=2)

group_labels = ['Group 1', 'Group 2', 'Group 3']
hist_data = [y1, y2, y3]

distplfig = ff.create_distplot(hist_data, group_labels, colors=colors,
                         bin_size=.2, show_rug=False)

for k in range(len(distplfig.data)):
    fig.add_trace(distplfig.data[k],
    row=2, col=2
)
fig.update_layout(barmode='overlay')
plotly.offline.plot(fig, filename='test.html')
#fig.show()

這取決於您如何構建 html 頁面。 如果它來自 plotly.offline.plot(fig, filename='name.html') 則不可能。 正如您提到的,子圖太小了,您可以在布局中使用高度和重量變量進行游戲:

關於布局:

from plotly.offline import plot
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
rows=3, cols=1, shared_xaxes=True, 
vertical_spacing=0.02)

fig.add_trace(go.Scatter(x=[0, 1, 2], y=[10, 11, 12]),
          row=3, col=1)

fig.add_trace(go.Scatter(x=[2, 3, 4], y=[100, 110, 120]),
          row=2, col=1)

fig.add_trace(go.Scatter(x=[3, 4, 5], y=[1000, 1100, 1200]),
          row=1, col=1)

fig.update_layout(height=1200, width=600,
              title_text="Stacked Subplots with Shared X-Axes")
fig['layout']['yaxis1'].update(domain=[0, 0.2])
fig['layout']['yaxis2'].update(domain=[0.3, 0.7])
fig['layout']['yaxis3'].update(domain=[0.8, 1])

plotly.offline.plot(fig, filename='name.html')

如果您自己構建 html 頁面,您可以將 html div 呈現為http://www.codingwithricky.com/2019/08/28/easy-django-plotly/並使用布局的高度和寬度變量使其更大或更小。

建立在@mil0s answer的基礎上,這是一個小函數,它需要幾個 plotly 圖像並將它們組合到一個 html 文件中,它們之間可能有一個分隔符,以及一個像 plotly 中的自動打開函數:

def combine_plotly_figs_to_html(plotly_figs, html_fname, include_plotlyjs='cdn', 
                                separator=None, auto_open=False):
    with open(html_fname, 'w') as f:
        f.write(plotly_figs[0].to_html(include_plotlyjs=include_plotlyjs))
        for fig in plotly_figs[1:]:
            if separator:
                f.write(separator)
            f.write(fig.to_html(full_html=False, include_plotlyjs=False))

    if auto_open:
        import pathlib, webbrowser
        uri = pathlib.Path(html_fname).absolute().as_uri()
        webbrowser.open(uri)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM