配置具有通用配置的子图轴

问题描述 投票:0回答:1

我想用相同的轴配置配置所有子图。下面的代码有效,但在子图增加时,我们需要添加更多 elif 来处理新的轴配置。如何简化此代码以处理以变量名作为参数的子图?

xaxis,yaxis = get_xyaxis()
for i,yname in enumerate(colnames):        
    trace1 = go.Scatter(
        x=df[xname],
        y=df[yname],           
        name=yname)      
    fig.add_trace(
        trace1,
        row=i+1,
        col=1
    )
    if i == 0:
        fig.update_layout(
            xaxis1=xaxis,
            yaxis1=yaxis,
        )
    elif i == 1:
        fig.update_layout(
            xaxis2=xaxis,
            yaxis2=yaxis,
        )
    elif i == 2:
        fig.update_layout(
            xaxis3=xaxis,
            yaxis3=yaxis,
        )

我试了

"xaxis%d"%(i + 1)=xaxis
但是没用!

完整代码:

进口再 将 pandas 导入为 pd

import plotly.graph_objects as go
from plotly.subplots import make_subplots

def plot_line(df,pngname):    
    fontsize = 10
    title = "demo"
    xlabel = "KeyPoint"
    ylabel = "Duration(secs)"
    xname = df.columns[0]
    colnames = df.columns[1:]
    
    n = len(colnames)

O

    fig = make_subplots(
        rows=n, cols=1,
        shared_xaxes=True,
        vertical_spacing = 0.02,
    )

    xaxis,yaxis = get_xyaxis()
    for i,yname in enumerate(colnames):        
        trace1 = go.Scatter(
            x=df[xname],
            y=df[yname],
            text=df[yname],
            textposition='top center',
            mode='lines+markers',            
            marker=dict(
                size=10,
                line=dict(width=0,color='DarkSlateGrey')),            
            name=yname)
        
        fig.add_trace(
            trace1,
            row=i+1,
            col=1
        )
        # TODO
        if i == 0:
            fig.update_layout(
                xaxis1=xaxis,
                yaxis1=yaxis,
            )
        elif i == 1:
            fig.update_layout(
                xaxis2=xaxis,
                yaxis2=yaxis,
            )
        elif i == 2:
            fig.update_layout(
                xaxis3=xaxis,
                yaxis3=yaxis,
            )
                            
    xpading=.05
    fig.update_layout(
        margin=dict(l=20,t=40,r=10,b=40),
        plot_bgcolor='#ffffff',#'rgb(12,163,135)',
        paper_bgcolor='#ffffff',        
        title=title,
        title_x=0.5,
        showlegend=True,
        legend=dict(x=.02,y=1.05),        
        barmode='group',
        bargap=0.05,
        bargroupgap=0.0,
        font=dict(
            family="Courier New, monospace",
            size=fontsize,
            color="black"
        ),
    )
    fig.show()
    return

def get_xyaxis():
    xaxis=dict(
        title_standoff=1,
        tickangle=-15,            
        showline=True,
        linecolor='black',
        color='black',
        linewidth=.5,
        ticks='outside',
        showgrid=True,
        gridcolor='grey',
        gridwidth=.5,
        griddash='solid',#'dot',            
    )
    yaxis=dict(
        title_standoff=1,
        showline=True,
        linecolor='black',
        color='black',
        linewidth=.5,            
        showgrid=True,
        gridcolor='grey',
        gridwidth=.5,
        griddash='solid',#'dot',
        zeroline=True,
        zerolinecolor='grey',
        zerolinewidth=.5,
        showticklabels=True,
    )        
    return [xaxis,yaxis]

def main():
    data = [
        ['AAA',1,2,3],
        ['BBB',3,2,3],
        ['CCC',2,1,2],
        ['DDD',4,2,3],
        ]

    df = pd.DataFrame(data,columns=['name','v1','v2','v3'])
    print(df)
    plot_line(df,"./demo.png")
    return
    
main()

输出:

python plotly
1个回答
0
投票

由于所有代码都已发布到您的问题,我将删除我的评论,因为它没有解决您的问题并改为回答。可以使用 Axis Update 将轴设置应用于所有子图。

import re
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

def plot_line(df,pngname):    
    fontsize = 10
    title = "demo"
    xlabel = "KeyPoint"
    ylabel = "Duration(secs)"
    xname = df.columns[0]
    colnames = df.columns[1:]
    
    n = len(colnames)
    fig = make_subplots(
        rows=n, cols=1,
        shared_xaxes=True,
        vertical_spacing = 0.02,
    )

    xaxis,yaxis = get_xyaxis()
    for i,yname in enumerate(colnames): 
        print(i)
        trace1 = go.Scatter(
            x=df[xname],
            y=df[yname],
            text=df[yname],
            textposition='top center',
            mode='lines+markers',            
            marker=dict(
                size=10,
                line=dict(width=0,color='DarkSlateGrey')),            
            name=yname)
        
        fig.add_trace(
            trace1,
            row=i+1,
            col=1
        )
        fig.update_xaxes(xaxis)
        fig.update_yaxes(yaxis)
        # TODO
        # if i == 0:
        #     fig.update_layout(
        #         xaxis1=xaxis,
        #         yaxis1=yaxis,
        #     )
        # elif i == 1:
        #     fig.update_layout(
        #         xaxis2=xaxis,
        #         yaxis2=yaxis,
        #     )
        # elif i == 2:
        #     fig.update_layout(
        #         xaxis3=xaxis,
        #         yaxis3=yaxis,
        #     )
                            
    xpading=.05
    fig.update_layout(
        margin=dict(l=20,t=40,r=10,b=40),
        plot_bgcolor='#ffffff',#'rgb(12,163,135)',
        paper_bgcolor='#ffffff',        
        title=title,
        title_x=0.5,
        showlegend=True,
        legend=dict(x=.02,y=1.05),        
        barmode='group',
        bargap=0.05,
        bargroupgap=0.0,
        font=dict(
            family="Courier New, monospace",
            size=fontsize,
            color="black"
        ),
    )
    fig.show()
    return

def get_xyaxis():
    xaxis=dict(
        title_standoff=1,
        tickangle=-15,            
        showline=True,
        linecolor='black',
        color='black',
        linewidth=.5,
        ticks='outside',
        showgrid=True,
        gridcolor='grey',
        gridwidth=.5,
        griddash='solid',#'dot',            
    )
    yaxis=dict(
        title_standoff=1,
        showline=True,
        linecolor='black',
        color='black',
        linewidth=.5,            
        showgrid=True,
        gridcolor='grey',
        gridwidth=.5,
        griddash='solid',#'dot',
        zeroline=True,
        zerolinecolor='grey',
        zerolinewidth=.5,
        showticklabels=True,
    ) 
    return [xaxis,yaxis]

def main():
    data = [
        ['AAA',1,2,3],
        ['BBB',3,2,3],
        ['CCC',2,1,2],
        ['DDD',4,2,3],
        ]

    df = pd.DataFrame(data,columns=['name','v1','v2','v3'])
    print(df)
    plot_line(df,"./demo.png")
    return
    
main()

© www.soinside.com 2019 - 2024. All rights reserved.