如何在Plotly Express中为两条折线分别设置虚线和实线?
解决Plotly Express设置多折线线型不生效的问题
你的问题出在line_dash_sequence参数需要配合line_dash参数一起使用,单独用的话Plotly不知道该把线型映射到哪个分组上。下面给你两种可行的解决方法:
方法1:转成长表格式(推荐,更符合Plotly Express的设计逻辑)
把宽表转成“变量-值”的长表结构,用power_type字段区分两条线,再通过line_dash绑定这个字段,就能让line_dash_sequence生效:
import pandas as pd import plotly.express as px from datetime import time df = pd.DataFrame( { "timestamp": [time(x) for x in range(24)], "power1": [50 * x for x in range(24)], "power2": [52 * x for x in range(24)], } ) # 转成长表 df_long = df.melt(id_vars="timestamp", var_name="power_type", value_name="power") fig = px.line( df_long, x="timestamp", y="power", color="power_type", # 用power_type区分颜色 color_discrete_sequence=["orange", "grey"], line_dash="power_type", # 用power_type区分线型 line_dash_sequence=["dash", "solid"], ) fig.show()
方法2:直接修改已生成的图表轨迹
如果不想改数据格式,可以直接遍历图表的data属性,手动给每条线设置线型:
import pandas as pd import plotly.express as px from datetime import time df = pd.DataFrame( { "timestamp": [time(x) for x in range(24)], "power1": [50 * x for x in range(24)], "power2": [52 * x for x in range(24)], } ) fig = px.line( df, x="timestamp", y=["power1", "power2"], color_discrete_sequence=["orange", "grey"], ) # 手动设置每条线的线型 fig.data[0].update(line=dict(dash="dash")) # 第一条线设为虚线 fig.data[1].update(line=dict(dash="solid")) # 第二条线设为实线 fig.show()
为什么原来的代码不生效?
line_dash_sequence是用来定义line_dash参数指定的离散变量对应的线型集合,当你没指定line_dash时,Plotly不会使用这个序列,所有线条都会默认用同一种线型。
内容的提问来源于stack exchange,提问作者0x0fba
相关产品推荐
相关产品推荐

