【问题标题】:Plotly: How to combine scatter and line plots using Plotly Express?Plotly:如何使用 Plotly Express 组合散点图和线图?
【发布时间】:2020-12-03 11:09:43
【问题描述】:

Plotly Express 以一种直观的方式以最少的代码行提供预先格式化的绘图;有点像 Seaborn 是如何为 matplotlib 做的。

可以在 Plotly 上添加绘图轨迹以在现有线图上获得散点图。但是,我在 Plotly Express 中找不到这样的功能。

是否可以在 Plotly Express 中结合散点图和折线图?

【问题讨论】:

    标签: python plotly plotly-python plotly-express


    【解决方案1】:

    你可以使用:

    fig3 = go.Figure(data=fig1.data + fig2.data)
    

    其中fig1fig2 分别使用px.line()px.scatter() 构建。如您所见,fig3 是使用 plotly.graph_objects 构建的。

    一些细节:

    我经常使用的一种方法是使用plotly.express 构建两个图形fig1fig2,然后使用它们的数据属性将它们与go.Figure / plotly.graph_objects 对象组合在一起,如下所示:

    import plotly.express as px
    import plotly.graph_objects as go
    df = px.data.iris()
    
    fig1 = px.line(df, x="sepal_width", y="sepal_length")
    fig1.update_traces(line=dict(color = 'rgba(50,50,50,0.2)'))
    
    fig2 = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
    
    fig3 = go.Figure(data=fig1.data + fig2.data)
    fig3.show()
    

    剧情:

    【讨论】:

    • 这是 Plotly 和 Dash 集成的最佳解决方案。谢谢!
    • 绝妙的解决方案!非常感谢
    • @NicoBako 感谢您的反馈!很高兴您发现它很有用。
    • 如果我有多个像 fig3 这样的数字,我该如何使用 add_trace?
    【解决方案2】:

    如果你想扩展方法

    fig3 = go.Figure(data=fig1.data + fig2.data)
    

    如其他答案所述,这里有一些提示。

    fig1.datafig2.data 是保存绘图所需的所有信息的常见元组,+ 只是将它们连接起来。

    # this will hold all figures until they are combined
    all_figures = []
    
    # data_collection: dictionary with Pandas dataframes
     
    for df_label in data_collection:
    
        df = data_collection[df_label]
        fig = px.line(df, x='Date', y=['Value'])
        all_figures.append(fig)
    
    import operator
    import functools
    
    # now you can concatenate all the data tuples
    # by using the programmatic add operator 
    fig3 = go.Figure(data=functools.reduce(operator.add, [_.data for _ in all_figures]))
    fig3.show()
    

    【讨论】:

    • 或者您可以附加fig.data,然后附加go.Figure(data=sum(all_figures, ()))。或者 go.Figure(data=sum((fig.data for fig in figures), ())) 如果您需要迭代两次。 ^^
    猜你喜欢
    • 2020-07-27
    • 2020-12-04
    • 2020-05-15
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多