Search code examples
pythondjangochartsplotly

Render Plotly chart without background


I have a Plotly donut chart rendering in my Django template that comes with a default white background. I can't figure out how to render it without the background.

I know how to make the background transparent but when I try to resize the chart, obviously the background is still there and it stretches the div or if I make the chart smaller so it fits then its too small and unreadable.

Is there a way to get rid of the background all together? Or maybe I should use something other than Plotly?

Thanks for your help!

    import plotly.graph_objects as go

    fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.3)])
    fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', width=300, height=300,)
    chart = fig.to_html()

Solution

  • You can change the margins of the plot. You might also want to move the legend. See below.

    import plotly.graph_objects as go
    
    labels = ['green','red','blue']
    values = [1,2,3]
    fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.3)])
        paper_bgcolor='rgba(0,0,0,0)', 
        width=300, 
        height=300)
    
    
    # Change margins
    fig.update_layout(
        autosize=False,
        margin=dict(
            l=2,
            r=0,
            b=1,
            t=1,
            pad=2
        ),
    )
    
    # Move legend
    fig.update_layout(legend=dict(
        yanchor="top",
        y=0.95,
        xanchor="left",
        x=0.87
    ))
    

    enter image description here