【问题标题】:Draw multiple CSV files in a HTML page using Plotly使用 Plotly 在 HTML 页面中绘制多个 CSV 文件
【发布时间】:2022-10-07 02:48:31
【问题描述】:

我想用fig = make_subplots(rows=.., cols=..) 在 HTML 页面上绘制多个 CSV 文件。

df1 = pd.read_csv(\'first_input.csv\')
fig1 = px.scatter(df, x=\"...\", y=\"...\", color=\"..\")

df2 = pd.read_csv(\'first_input.csv\')
fig2 = px.scatter(df, x=\"...\", y=\"...\", color=\"..\")

    标签: python plotly plotly-python


    【解决方案1】:

    不幸的是plotly subplots 不直接支持plotly.express 数字,如文档here 中所述。

    但是,当您使用 fig1 = px.scatter(df, x="...", y="...", color="..") 创建 plotly.express 图形时,实际上是在创建一个图形,其中 fig1.datago.Scatter 跟踪的元组。您可以访问 fig1.data 中的每个跟踪并将其添加到您的 subplots 对象。

    如果您有多个 px.scatter 图形,则可以遍历它们,并将 px.scatter 图形中的每个跟踪添加到您的 subplots 对象的相应行和列。然后我们可以将每个 px.scatter 图形中的轴标题添加到 subplots 对象布局中。

    我将使用tips 示例数据集来演示:

    import plotly.express as px
    from plotly.subplots import make_subplots
    df = px.data.tips()
    
    fig1 = px.scatter(df, x="total_bill", y="tip", color="smoker")
    fig2 = px.scatter(df, x="total_bill", y="tip", color="day")
    
    fig_subplots = make_subplots(rows=2, cols=1)
    
    for trace in fig1.data:
        fig_subplots.add_trace(
            trace,
            row=1, col=1
        )
    for trace in fig2.data:
        fig_subplots.add_trace(
            trace,
            row=2, col=1
        )
    
    ## x and y axies in fig_subplots["layout"] are called xaxis, xaxis2, ..., yaxis, yaxis2, ...
    ## here we are making the assumption you are stacking your plots vertically
    def modify_axis_titles(fig_subplots, px_fig, nrow):
        xaxis_name, yaxis_name = f"xaxis{nrow}", f"yaxis{nrow}"
        fig_subplots['layout'][xaxis_name]['title'] = px_fig.layout['xaxis']['title']
        fig_subplots['layout'][yaxis_name]['title'] = px_fig.layout['yaxis']['title']
            
    for px_fig, nrow in zip([fig1, fig2],[1,2]):
        modify_axis_titles(fig_subplots, px_fig, nrow)
    
    fig_subplots.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2020-04-03
      • 2017-07-20
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 2014-07-18
      相关资源
      最近更新 更多