St.plotly_chart shows small gap between the axis and chart

I am using st.plotly_chart to display a plotly graph. However when displayed through stream lit there is a small gap between the axis and the graph itself (issue isn’t there when run in a local python script with just fig.show().

I am simply using:

st.plotly_chart(fig)

Any ideas of how to get rid of this blank space?

Hi @Geo_D

Do you have a screenshot from fig.show() as a comparison in relation to the one from st.plotly_chart(). Typically all granular adjustments to spacings and margins could be explicitly defined via plotly parameters.

Hi, here is how it plots uses fig.show():

st.plotly_chart defaults to a “streamlit” theme. Passing None to the theme argument should give you back plotly’s default theme which does not add that weird padding.


If you still want to use streamlit’s theme, you’d need to adjust the pad of your figure layout. Just be aware that the axis lines are not necessarily the zero lines.

Code:
import streamlit as st
import plotly.graph_objects as go

fig = go.Figure()

# Update axes properties
fig.update_xaxes(
    range=[0, 10],
    showline=True, linewidth=2, linecolor='red',
    zeroline=True, zerolinewidth=2, zerolinecolor='black',
)

fig.update_yaxes(
    range=[0, 10],
    showline=True, linewidth=2, linecolor='blue',
    zeroline=True, zerolinewidth=2, zerolinecolor='black'
)

fig.update_layout(
    height=500,
    title_text="Streamlit default",
    shapes=[
        # Circle
        dict(
            type="circle",
            line_color="gray", fillcolor=None,
            xref="x", yref="y",
            x0=2, y0=-3, x1=8, y1=3
        ),
        # Cubic Bezier Curves
        dict(
            type="path",
            path="M 1,4 C 2,8 6,4 8,8",
            line_color="MediumPurple",
            line_width=5,
        ),
    ]
)


cols = st.columns(2)

with cols[0]:
    st.plotly_chart(fig, use_container_width=True)

with cols[1]:
    fig.update_layout(
        margin=dict(pad=0),
        title_text="Fixing padding",
    )
    st.plotly_chart(fig, use_container_width=True)
1 Like