Search code examples
plotlylegendlegend-properties

Showing or saving only the legend of a plotly figure


Given a plotly figure with traces and a legend, is there a way to only show the legend without any of the plot content?

My use case for this: I'm exporting several images with the same legend. Instead of exporting the figure with the legend, I'd like to export the plot area and the legend separately. This would give me the flexibility to embed these images in presentations - perhaps resizing the legend, perhaps not including it, moving it around, etc.


Solution

  • Try the following:

    import plotly.graph_objects as go
    import plotly.io as pio
    
    # Create your traces
    trace1 = go.Scatter(
        x=[1, 2, 3], 
        y=[4, 5, 6], 
        mode='lines', 
        name='Trace 1',
        visible='legendonly'
    )
    trace2 = go.Scatter(
        x=[1, 2, 3], 
        y=[6, 5, 4], 
        mode='lines', 
        name='Trace 2',
        visible='legendonly'
    )
    
    # Create the figure with the traces
    fig = go.Figure()
    fig.add_trace(trace1)
    fig.add_trace(trace2)
    
    # Update layout to remove the plot area and axes
    fig.update_layout(
        xaxis=dict(
            showline=False,
            showgrid=False,
            showticklabels=False,
            zeroline=False
        ),
        yaxis=dict(
            showline=False,
            showgrid=False,
            showticklabels=False,
            zeroline=False
        ),
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        showlegend=True,
        legend=dict(
            x=0,  # Adjust legend position as needed
            y=1   # Adjust legend position as needed
        )
    )
    
    # Remove margins
    fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
    
    # Save the figure with only the legend
    pio.write_image(fig, 'legend_only.png')
    
    # Show the figure (optional)
    fig.show()
    

    You might need to install the kaleido package if you don't have it already.