Skip to main content
 首页 » 编程设计

Python plotly之设置轨迹相等,除了新轨迹有图例

2025年02月15日7langtianya

我目前正在尝试基于旧轨迹创建新轨迹,但我希望第二条轨迹关闭图例。跟踪 1 的代码是:

import plotly.graph_objs as go 
 
trace = go.Scatter( 
    x=x, 
    y=y, 
    mode='lines', 
    name='INC', 
    line = dict( 
        color = ('rgb(0,153,255)'), 
        ) 
) 

我如何创建 trace2 使其等于 trace 除了它包含 showlegend=false ?本质上,我希望 trace2 是:

trace2 = go.Scatter( 
        x=x, 
        y=y, 
        mode='lines', 
        name='INC', 
        showlegend=false, 
        line = dict( 
            color = ('rgb(0,153,255)'), 
            ) 
    ) 

我必须对几条轨迹执行此操作。在键入 trace2=trace 后是否有我可以使用的快捷方式,这将是等效的?谢谢

请您参考如下方法:

您可以使用方法 copy() 轻松实现这一点并添加您想要的键,就像在一个简单的字典中一样:

trace = go.Scatter( 
    x=x, 
    y=y, 
    mode='lines', 
    name='INC', 
    line = dict( 
        color = ('rgb(0,153,255)'), 
        ) 
) 
 
trace2 = trace.copy() 
trace2['showlegend']=False 
print(trace) 
print(trace2) 
 
# >>>{'type': 'scatter', 'y': 3, 'mode': 'lines', 'x': 2, 'name': 'INC', 'line': {'color': 'rgb(0,153,255)'}} 
# >>>{'showlegend': False, 'type': 'scatter', 'y': 3, 'mode': 'lines', 'x': 2, 'name': 'INC', 'line': {'color': 'rgb(0,153,255)'}}