簡體   English   中英

如何使用 plotly express 創建子圖?

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

一直喜歡 plotly 表達圖,但現在想用它們創建一個儀表板。 沒有找到這方面的任何文檔。 這可能嗎?

我也在努力尋找對此的回應,所以我最終不得不創建自己的解決方案(請參閱我的完整細分: 如何使用 Plotly Express 創建子圖

本質上make_subplots()接受繪圖跟蹤來制作子圖,而不是像 Express 返回的圖形對象。 因此,您可以做的是,在 Express 中創建圖形后,將 Express 圖形對象分解為它們的軌跡,然后將它們的軌跡重新組合成子圖。

代碼:

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)

輸出:

在此處輸入圖像描述

從文檔:

**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.

在這里也有一些例子。

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

不幸的是,目前還不是。 請參閱以下問題以獲取更新: https ://github.com/plotly/plotly_express/issues/83

解決@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)

這很容易擴展到列維度。

我通過將所有數據組合在一個數據框中來解決它,並使用一個名為“type”的列來區分這兩個圖。 然后我使用facet_col創建(某種)子圖:

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

在此處輸入圖像描述

試試這個 function。 您必須將 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