我有由 px.timeline 绘制的甘特图,运行良好,如下图所示。因为它会相互重叠并且也可以更容易地使用透明颜色进行审查。
但是当我想将它添加为子图时,它显示了一些错误,因为红色窗口消失了,如下图
这是完整的代码,您可以在此处注释和取消注释 2 行以查看不同之处
# fig = trace_1 #uncomment this line to see the difference
fig.add_trace(trace_1.data[0], row=1, col=1) #comment this line to see the difference
import pandas as pd
import plotly.express as px
from plotly.subplots import make_subplots
df = pd.DataFrame({
'Task': ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5', 'Task 6'],
'Start': [pd.Timestamp('2022-01-01'), pd.Timestamp('2022-01-02'), pd.Timestamp('2022-01-03'), pd.Timestamp('2022-01-03'), pd.Timestamp('2022-01-05'), pd.Timestamp('2022-01-04')],
'Finish': [pd.Timestamp('2022-01-02'), pd.Timestamp('2022-01-04'), pd.Timestamp('2022-01-05'), pd.Timestamp('2022-01-08'), pd.Timestamp('2022-01-06'), pd.Timestamp('2022-01-07')],
'Resource': ['Resource 1', 'Resource 2', 'Resource 3', 'Resource 4', 'Resource 4', 'Resource 4'],
'Type': ['Type_Blue', 'Type_Blue', 'Type_Red', 'Type_Blue', 'Type_Blue', 'Type_Red']
})
fig = make_subplots(rows=2, shared_xaxes=True)
trace_1 = px.timeline(df, x_start='Start', x_end='Finish', y='Resource',
color='Type', color_discrete_map={'Type_Blue': 'blue', 'Type_Red': 'red'}, opacity=0.2)
# fig = trace_1 #uncomment this line to see the difference
fig.add_trace(trace_1.data[0], row=1, col=1) #comment this line to see the difference
fig.update_yaxes(autorange="reversed")
fig.update_layout(title='Timeline Subplots')
fig.update_xaxes(type='date')
fig.show()
谢谢。
express 创建的图形由两个条形图组成,作为其内部结构。由于第一个数据是子图中指定的数据,因此只显示一个。另外,express 有一个 facet 函数,所以最容易指定它。我也会回答那个例子。
fig = make_subplots(rows=2, shared_xaxes=True)
trace_1 = px.timeline(df, x_start='Start', x_end='Finish', y='Resource',
color='Type', color_discrete_map={'Type_Blue': 'blue', 'Type_Red': 'red'}, opacity=0.2)
# fig = trace_1 #uncomment this line to see the difference
fig.add_trace(trace_1.data[0], row=1, col=1)
fig.add_trace(trace_1.data[1], row=2, col=1)
fig.update_yaxes(autorange="reversed")
fig.update_layout(title='Timeline Subplots')
fig.update_xaxes(type='date')
fig.show()
小排
fig = px.timeline(df,
x_start='Start',
x_end='Finish',
y='Resource',
color='Type',
facet_row='Type',
color_discrete_map={'Type_Blue': 'blue', 'Type_Red': 'red'},
opacity=0.2
)
fig.update_yaxes(autorange="reversed")
fig.update_layout(title='Timeline Subplots')
fig.update_xaxes(type='date')
fig.show()