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.