仅显示或保存绘图图的图例

问题描述 投票:0回答:1

给定一个带有痕迹和图例的情节图形,有没有办法显示图例而不显示任何情节内容?

我的用例:我正在导出具有相同图例的多个图像。我不想导出带有图例的图形,而是想分别导出绘图区域和图例。这将使我能够灵活地将这些图像嵌入到演示文稿中 - 也许调整图例的大小,也许不包括它,移动它,等等。

plotly legend legend-properties
1个回答
0
投票

尝试以下操作:

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()

如果您还没有安装

kaleido
软件包,您可能需要安装它。

© www.soinside.com 2019 - 2024. All rights reserved.