简体   繁体   English

如何使用 plotly express 创建子图?

[英]how can i create subplots with plotly express?

been loving the plotly express graphs but want to create a dashboard with them now.一直喜欢 plotly 表达图,但现在想用它们创建一个仪表板。 Did not find any documentation for this.没有找到这方面的任何文档。 Is this possible?这可能吗?

I was struggling to find a response on this as well so I ended up having to create my own solution (see my full breakdown here: How To Create Subplots Using Plotly Express )我也在努力寻找对此的回应,所以我最终不得不创建自己的解决方案(请参阅我的完整细分: 如何使用 Plotly Express 创建子图

Essentially make_subplots() takes in plot traces to make the subplots instead of figure objects like that which Express returns.本质上make_subplots()接受绘图跟踪来制作子图,而不是像 Express 返回的图形对象。 So what you can do is, after creating your figures in Express, is break apart the Express figure objects into their traces and then re-assemble their traces into subplots.因此,您可以做的是,在 Express 中创建图形后,将 Express 图形对象分解为它们的轨迹,然后将它们的轨迹重新组合成子图。

Code:代码:

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)

Output:输出:

在此处输入图像描述

From the docs:从文档:

**facet_row**
(string: name of column in data_frame) Values from this column are used to assign marks to facetted subplots in the vertical direction.
**facet_col**
(string: name of column in data_frame) Values from this column are used to assign marks to facetted subplots in the horizontal direction.

Get here some examples too.在这里也有一些例子。

https://medium.com/@plotlygraphs/introducing-plotly-express-808df010143d https://medium.com/@plotlygraphs/introducing-plotly-express-808df010143d

Unfortunately, it is not at the moment.不幸的是,目前还不是。 See the following issue to get updated: https://github.com/plotly/plotly_express/issues/83请参阅以下问题以获取更新: https ://github.com/plotly/plotly_express/issues/83

Working off @mmarion's solution:解决@mmarion 的解决方案:

import plotly.express as px
from plotly.offline import plot
from plotly.subplots import make_subplots

figures = [
            px.line(df1),
            px.line(df2)
    ]

fig = make_subplots(rows=len(figures), cols=1) 

for i, figure in enumerate(figures):
    for trace in range(len(figure["data"])):
        fig.append_trace(figure["data"][trace], row=i+1, col=1)
        
plot(fig)

This is easily extended into the column dimension.这很容易扩展到列维度。

I solved it by combining all the data in a single dataframe, with a column called "type" that distinguishes the two plots.我通过将所有数据组合在一个数据框中来解决它,并使用一个名为“type”的列来区分这两个图。 Then I used facet_col to create (some kind of) subplot:然后我使用facet_col创建(某种)子图:

px.scatter(df3, x = 'dim1', y = 'dim2', color = 'labels', facet_col='type') px.scatter(df3, x = 'dim1', y = 'dim2', 颜色 = 'labels', facet_col='type')

在此处输入图像描述

Try this function out.试试这个 function。 You have to pass in the plotly express figures into the function and it returns a subplot figure.您必须将 plotly 快递数字传递到 function 中,它会返回一个子图数字。

#quick_subplot function
def quick_subplot(n,nrows,ncols, *args): #n:number of subplots, nrows:no.of. rows, ncols:no of cols, args
    from dash import dcc
    import plotly.subplots as sp
    from plotly.subplots import make_subplots

    fig=[] #list to store figures
    for arg in args:
        fig.append(arg)

    
    combined_fig_title=str(input("Enter the figure title: "))
    tok1=int(input("Do you want to disable printing legends after the first legend is printed ? {0:Disable, 1:Enable} : "))

    fig_traces={} #Dictionary to store figure traces
    subplt_titles=[]

    #Appending the traces of the figures to a list in fig_traces dictionary
    for i in range(n):
        fig_traces[f'fig_trace{i}']=[]

        for trace in range(len(fig[i]["data"])):
            fig_traces[f'fig_trace{i}'].append(fig[i]["data"][trace])
            if(i!=0 & tok1==0):
                fig[i]["data"][trace]['showlegend'] = False #Disabling other legends

        subplt_titles.append(str(input(f"Enter subplot title for subplot-{i+1}: ")))
    
    #Creating a subplot
        #Change height and width of figure here if necessary
    combined_fig=sp.make_subplots(rows = nrows, cols = ncols, subplot_titles = subplt_titles)
    combined_fig.update_layout(height = 500, width = 1200, title_text = '<b>'+combined_fig_title+'<b>', title_font_size = 25)
    
    #Appending the traces to the newly created subplot
    i=0
    for a in range(1,nrows+1):
        for b in range(1, ncols+1):
            for traces in fig_traces[f"fig_trace{i}"]:
                combined_fig.append_trace(traces, row=a, col=b)
            i+=1
            
            
    #Setting axis titles       
        #X-axis
    combined_fig['layout']['xaxis']['title']['font']['color']='blue'
    tok2=int(input("Separate x-axis titles?{0:'No',1:'Yes'}: "))
    
    for i in range(max(nrows,ncols)):
        if i==0:
            combined_fig['layout']['xaxis']['title']=str(input(
            f"Enter x-axis's title: "))

        if tok2 & i!=0:
            combined_fig['layout'][f'xaxis{i+1}']['title']=str(input(
            f"Enter x-axis {i+1}'s title: "))
            combined_fig['layout'][f'xaxis{i+1}']['title']['font']['color']='blue'
                
            
        
        #Y-axis
    combined_fig['layout']['yaxis']['title']['font']['color']='blue'
    tok3=int(input("Separate y-axis titles?{0:'No',1:'Yes'}: "))
    
    for i in range(max(nrows,ncols)):
        if i==0:
            combined_fig['layout']['yaxis']['title']=str(input(
            f"Enter y-axis's title: "))
            
        if tok3 & i!=0:
            combined_fig['layout'][f'yaxis{i+1}']['title']=str(input(
            f"Enter y-axis {i+1}'s title: "))

            combined_fig['layout'][f'yaxis{i+1}']['title']['font']['color']='blue'

                
                
    combined_fig['layout']['xaxis']['title']['font']['color']='blue'               
    combined_fig['layout']['yaxis']['title']['font']['color']='blue'
    
    
    return combined_fig


f=quick_subplot(2,1,2,fig1,fig2)
f.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM