You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除Streamlit应用左右边距并横向排列图表?

解决Streamlit图表左右空白边距及横向排列问题

一、去除全局应用左右边距

Streamlit默认给页面主体加了左右内边距,可通过自定义CSS直接覆盖:

st.markdown("""
<style>
    .main .block-container {
        padding-left: 0.5rem;
        padding-right: 0.5rem;
    }
</style>
""", unsafe_allow_html=True)

把这段代码放在st.title之前,padding-left和padding-right的数值可按需调整,设为0就能完全去掉边距。

二、优化Matplotlib图表内部空白

原代码里的Matplotlib图表默认有较多冗余空白,可通过以下方式压缩:

  • 创建画布时指定合适尺寸
  • 用tight_layout()自动调整布局
  • 开启自适应容器宽度

修改后的plot函数:

def plot(dataframe):
    # 自定义画布尺寸,减少多余空白
    fig, ax = plt.subplots(1, 1, figsize=(8, 4))
    ax.scatter(x=dataframe['Depth'], y=dataframe['Magnitude'])
    ax.set_xlabel('深度')
    ax.set_ylabel('震级')
    # 自动调整图表元素位置,消除内部空白
    plt.tight_layout()
    # 让图表自适应容器宽度
    st.pyplot(fig, use_container_width=True)

三、优化Plotly图表边距

Plotly的空白可通过update_layout直接设置边距参数,修改interactive_plot函数:

def interactive_plot(dataframe):
    x_axis_val = st.selectbox('选择X轴属性', options=df.columns)
    y_axis_val = st.selectbox('选择Y轴属性', options=df.columns)
    col = st.color_picker('选择图表颜色')
    
    plot = px.scatter(dataframe, x=x_axis_val, y=y_axis_val)
    plot.update_traces(marker=dict(color=col))
    # 去除左右边距,上下保留少量边距避免内容截断
    plot.update_layout(margin=dict(l=0, r=0, t=30, b=30))
    # 开启自适应容器宽度
    st.plotly_chart(plot, use_container_width=True)

四、实现图表横向排列

用st.columns创建列布局,就能把多个图表并排显示,比如在主页同时展示两个图表:

# 示例:在主页横向排列两个图表
if options == '主页':
    col1, col2 = st.columns(2)
    with col1:
        st.subheader('深度 vs 震级')
        plot(df)
    with col2:
        st.subheader('交互式图表预览')
        preview_plot = px.scatter(df, x='Depth', y='Magnitude')
        preview_plot.update_layout(margin=dict(l=0, r=0, t=30, b=30))
        st.plotly_chart(preview_plot, use_container_width=True)

完整修改后代码

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import plotly_express as px

# 去除全局左右边距的自定义CSS
st.markdown("""
<style>
    .main .block-container {
        padding-left: 0.5rem;
        padding-right: 0.5rem;
    }
</style>
""", unsafe_allow_html=True)

def stats(dataframe):
    st.header('数据统计')
    st.write(dataframe.describe())
    
def data_header(dataframe):
    st.header('数据预览')
    st.write(dataframe.head())
    
def plot(dataframe):
    fig, ax = plt.subplots(1, 1, figsize=(8, 4))
    ax.scatter(x=dataframe['Depth'], y=dataframe['Magnitude'])
    ax.set_xlabel('深度')
    ax.set_ylabel('震级')
    plt.tight_layout()
    st.pyplot(fig, use_container_width=True)
    
def interactive_plot(dataframe):
    x_axis_val = st.selectbox('选择X轴属性', options=df.columns)
    y_axis_val = st.selectbox('选择Y轴属性', options=df.columns)
    col = st.color_picker('选择图表颜色')
    
    plot = px.scatter(dataframe, x=x_axis_val, y=y_axis_val)
    plot.update_traces(marker=dict(color=col))
    plot.update_layout(margin=dict(l=0, r=0, t=30, b=30))
    st.plotly_chart(plot, use_container_width=True)

st.title('地震数据探索器')
st.text('这是一个用于探索地震数据的Web应用')

st.sidebar.title('导航')
uploaded_file = st.sidebar.file_uploader('在此上传你的数据文件')

options = st.sidebar.radio('页面', options=['主页', '数据统计', '数据预览', '静态图表', '交互式图表'])

df = pd.read_csv('/Users/deisert/Documents/FAA-Sabin/Dashboard/kaggle_significant_earthquakes_database.csv')

if options == '数据统计':
    stats(df)
elif options == '数据预览':
    data_header(df)
elif options == '静态图表':
    plot(df)
elif options == '交互式图表':
    interactive_plot(df)
elif options == '主页':
    col1, col2 = st.columns(2)
    with col1:
        st.subheader('深度 vs 震级')
        plot(df)
    with col2:
        st.subheader('交互式图表预览')
        preview_plot = px.scatter(df, x='Depth', y='Magnitude')
        preview_plot.update_layout(margin=dict(l=0, r=0, t=30, b=30))
        st.plotly_chart(preview_plot, use_container_width=True)

关键说明

  • use_container_width=True:让图表自适应所在容器宽度,避免出现多余空白
  • 自定义CSS的.main .block-container:针对Streamlit主体容器调整内边距,数值可按需修改
  • Matplotlib的plt.tight_layout():自动调整图表元素位置,减少内部空白
  • Plotly的margin参数:直接设置上下左右边距数值,0表示完全去除对应方向的空白

内容的提问来源于stack exchange,提问作者325

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:55:00