如何使用 Plotly Express 创建子图 [英] How To Create Subplots Using Plotly Express

查看:202
本文介绍了如何使用 Plotly Express 创建子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你和我一样,你喜欢 Plotly Express,但是当你遇到 Express 返回的数字不能使用make_subplots()"的问题时,你感到很沮丧,因为 make_subplots 接收的是轨迹而不是数字.在这篇文章中,我想分享我自己的解决方案,关于我如何仅使用 Plotly Express(和 plotly.subplots)创建包含两种不同类型图形(如下所示)的子图

If you’re like me, you love Plotly Express, but were frustrated when you ran into the issue that figures returned by Express can’t utilize ‘make_subplots()’ since make_subplots takes in traces and not figures. With this post, I’d like to share my own solution on how I created a subplot containing two different types of figures (like below) using only Plotly Express (and plotly.subplots)

推荐答案

解决方案:

import plotly.express as px
import plotly.subplots as sp

# Create figures in Express
figure1 = px.line(my_df)
figure2 = px.bar(my_df)

# For as many traces that exist per Express figure, get the traces from each plot and store them in an array.
# This is essentially breaking down the Express fig into it's traces
figure1_traces = []
figure2_traces = []
for trace in range(len(figure1["data"])):
    figure1_traces.append(figure1["data"][trace])
for trace in range(len(figure2["data"])):
    figure2_traces.append(figure2["data"][trace])

#Create a 1x2 subplot
this_figure = sp.make_subplots(rows=1, cols=2) 

# Get the Express fig broken down as traces and add the traces to the proper plot within in the subplot
for traces in figure1_traces:
    this_figure.append_trace(traces, row=1, col=1)
for traces in figure2_traces:
    this_figure.append_trace(traces, row=1, col=2)

#the subplot as shown in the above image
final_graph = dcc.Graph(figure=this_figure)

由于我正在处理的项目数据的敏感性,我无法分享我的程序输出的实际图像,但它看起来与上图中的一模一样.据我测试,这应该适用于任何 Express 数字.

I couldn’t share an actual image of my program’s output due to the sensitivity of the data of the project I’m working on, but it looks exactly like the one in the above image. As far as I’ve tested this should work with any Express figure.

我希望这对某些人有用.祝大家绘图愉快!

I hope this can be of use to some. Happy plotting everyone!

这篇关于如何使用 Plotly Express 创建子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆