如何在Plotly Express甘特图中整合表格或优化信息展示?
问题描述
我用Plotly Express创建了甘特图,代码如下:
fig = px.timeline(short_term, x_start="Starting Date2", x_end="Ending Date2", y="Concat",color="Input Quantity", text="Input Quantity",title = "Production Plan") fig.add_vline(x=date, line_width=3, line_color="black") fig.update_yaxes(autorange="reversed") # 否则任务会从下往上排列 fig.show()
当前y轴使用的Concat字段是拼接多类信息的字符串,这种方式不够优雅。想请教:是否可以在甘特图左侧添加表格展示详细信息,或者用其他更美观的方式把信息整合到图中?
当前效果示意图:
方案1:左侧添加表格(Plotly子图实现)
通过plotly.subplots.make_subplots创建表格+甘特图的组合布局,左侧表格展示详细信息,右侧甘特图保留时间轴,两者y轴对齐保证任务一一对应。
示例代码:
import plotly.express as px import plotly.subplots as sp import plotly.graph_objects as go # 假设你的数据集包含Product、Batch等需要展示的字段 short_term = ... # 你的数据集 # 创建基础甘特图 gantt_fig = px.timeline(short_term, x_start="Starting Date2", x_end="Ending Date2", y="Concat", color="Input Quantity", text="Input Quantity") gantt_fig.add_vline(x=date, line_width=3, line_color="black") gantt_fig.update_yaxes(autorange="reversed") # 定义表格列和数据 table_cols = ["Product", "Batch", "Input Quantity"] table_data = [short_term[col].tolist() for col in table_cols] # 创建表格组件 table = go.Table( header=dict(values=table_cols, fill_color='lightgrey', align='left'), cells=dict(values=table_data, fill_color='white', align='left') ) # 组合子图,左侧表格占20%宽度,右侧甘特图占80% fig = sp.make_subplots(rows=1, cols=2, column_widths=[0.2, 0.8], specs=[[{"type": "table"}, {"type": "xy"}]]) # 添加表格和甘特图到布局 fig.add_trace(table, row=1, col=1) for trace in gantt_fig.data: fig.add_trace(trace, row=1, col=2) # 同步y轴并优化布局 fig.update_yaxes(autorange="reversed", row=1, col=2) fig.update_layout(title_text="Production Plan", height=600) fig.add_vline(x=date, line_width=3, line_color="black", row=1, col=2) fig.show()
方案2:增强Hover提示框展示信息
简化y轴显示(比如只保留任务ID),把所有详细信息整合到hover提示框中,鼠标悬停即可查看完整内容。
示例代码:
import plotly.express as px fig = px.timeline(short_term, x_start="Starting Date2", x_end="Ending Date2", y="Task ID", # 替换为简洁的核心标识字段 color="Input Quantity", text="Input Quantity", title = "Production Plan", hover_data={ "Task ID": False, # 隐藏重复字段 "Starting Date2": True, "Ending Date2": True, "Input Quantity": True, "Product": True, # 添加需要展示的其他字段 "Batch": True }) fig.add_vline(x=date, line_width=3, line_color="black") fig.update_yaxes(autorange="reversed") fig.show()
方案3:自定义Y轴刻度标签
保留y轴展示信息,但用换行排版替代生硬的字符串拼接,让标签更清晰美观。
示例代码:
import plotly.express as px # 生成带换行的自定义y轴标签 short_term["Y_Label"] = short_term.apply( lambda row: f"{row['Product']}\nBatch: {row['Batch']}\nQty: {row['Input Quantity']}", axis=1 ) fig = px.timeline(short_term, x_start="Starting Date2", x_end="Ending Date2", y="Y_Label", color="Input Quantity", text="Input Quantity", title = "Production Plan") fig.add_vline(x=date, line_width=3, line_color="black") fig.update_yaxes(autorange="reversed", tickfont={"size": 10}) # 调整字体适配换行 fig.show()
内容的提问来源于stack exchange,提问作者Morten_DK
相关产品推荐
相关产品推荐

