Skip to main content
 首页 » 编程设计

python之在 plotly 中从底部给图形空间

2024年12月31日7tuyile006

我正在使用此代码在一个图中绘制两个图,但我无法弄清楚如何从底部到图形留出空间。

def visualize_trends(df, features, titles, fig_title, fn, vs = 0.18, h = 1000, w = 800): 
 
    trace0 = go.Scatter( 
        x = df[features[0]], 
        y = df['Past_Developers_Count'], 
        mode = 'lines+markers', 
        name = 'Past', 
    ) 
 
    trace1 = go.Scatter( 
        x = df[features[1]], 
        y = df['Future_Developers_Count'], 
        mode = 'lines+markers', 
        name = 'Future', 
    ) 
 
    fig = tools.make_subplots(rows = 2, cols = 1, vertical_spacing = vs, subplot_titles = titles) 
 
    fig.append_trace(trace0, 1, 1) 
    fig.append_trace(trace1, 2, 1) 
 
    fig['layout'].update(height = h, width = w, paper_bgcolor = 'rgb(233,233,233)', title = fig_title) 
 
    py.iplot(fig, filename = fn) 

输出:

有没有像我用vertical_spacing给两个图留空间一样留空间的参数?

请您参考如下方法:

我自己想通了。您可以给 margin 以提供所需的空间。在 margin 中,您可以指定 left, right, bottom, up 各个方向的空间。

margin = dict(l = 10, r = 20, b = 30, u = 40) 

您可以根据自己的要求传值。在我的案例中,我确实喜欢这样做,以便从底部留出空间,

margin = dict(b = 140) 

功能齐全,

def visualize_trends(df, features, titles, fig_title, fn, vs = 0.18, h = 1000, w = 800): 
 
    trace0 = go.Scatter( 
        x = df[features[0]], 
        y = df['Past_Developers_Count'], 
        mode = 'lines+markers', 
        name = 'Past', 
    ) 
 
    trace1 = go.Scatter( 
        x = df[features[1]], 
        y = df['Future_Developers_Count'], 
        mode = 'lines+markers', 
        name = 'Future', 
    ) 
 
    fig = tools.make_subplots(rows = 2, cols = 1, vertical_spacing = vs, subplot_titles = titles) 
 
    fig.append_trace(trace0, 1, 1) 
    fig.append_trace(trace1, 2, 1) 
 
    fig['layout'].update(height = h, width = w, margin = dict(b = 140),  
                         paper_bgcolor = 'rgb(233,233,233)', title = fig_title) 
 
    py.iplot(fig, filename = fn) 

输出:

注意:我发布这个答案是为了让其他人可以在这个问题上节省时间。