简体   繁体   English

将 go.Scatter plots 和 gantt plot 添加到相同的 plotly subplot

[英]Add go.Scatter plots and gantt plot to the same plotly subplot

Is it possible to add a gantt plot to a fig created with make_subplots that contains go.Scatter time series plots.是否可以将甘特图 plot 添加到使用包含 go.Scatter 时间序列图的 make_subplots 创建的图。 I have set shared_xaxes=true and fixedrange=True for the y-axis in the subplot, so the go.Scatter plots are linked and zoom in and out together on the x-axis.我已经为子图中的 y 轴设置了 shared_xaxes=true 和 fixedrange=True,因此 go.Scatter plots 被链接起来并在 x 轴上一起放大和缩小。

My goal, at a minimum, is to line the x-axis of the go.Scatter plots up with the x-axis of the gantt plot. Currently I have added the subplot and the gantt plot, created by px.timeline, to an HTML page as two separate figures and they don't quite line up.我的目标至少是将 go 的 x 轴对齐。散点图与甘特图 plot 的 x 轴对齐。目前我已经将由 px.timeline 创建的子图和甘特图 plot 添加到HTML 页面作为两个单独的数字,它们并没有完全对齐。 Ideally I would like the x-axis of the gantt plot to be linked to the go.Scatter plots so they zoom in and out together.理想情况下,我希望甘特图 plot 的 x 轴链接到 go.Scatter 图,以便它们一起放大和缩小。

Building off of Rob's answer and in response to Derek's comment, here is an example of what I am trying to do with sub plots.基于 Rob 的回答和对 Derek 的评论的回应,这里是我尝试对子图进行处理的示例。

import plotly.express as px
import pandas as pd
import numpy as np
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=2, cols=1, subplot_titles = ('Scatter1', 'Scatter2'), shared_xaxes=True)

df = pd.DataFrame(
    [
        dict(Task="Job A", Start="2009-01-01", Finish="2009-02-28", Resource="Alex"),
        dict(Task="Job B", Start="2009-03-05", Finish="2009-04-15", Resource="Alex"),
        dict(Task="Job C", Start="2009-02-20", Finish="2009-05-30", Resource="Max"),
    ]
)
df["Start"] = pd.to_datetime(df["Start"])
df["Finish"] = pd.to_datetime(df["Finish"])


fig2 = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Resource")
#fig2.update_yaxes(autorange="reversed")

df2 = pd.DataFrame(
    {
        "Date": pd.date_range(
            df.loc[:, ["Start", "Finish"]].values.min(),
            df.loc[:, ["Start", "Finish"]].values.max(),
            freq="W-MON",
        )
    }
).pipe(lambda d: d.assign(Value=np.random.randint(1, 20, len(d))))

df3 = pd.DataFrame(
    {
        "Date": pd.date_range(
            df.loc[:, ["Start", "Finish"]].values.min(),
            df.loc[:, ["Start", "Finish"]].values.max(),
            freq="W-MON",
        )
    }
).pipe(lambda d: d.assign(Value=np.random.randint(1, 20, len(d))))
trace1 = go.Scatter(x=df2.Date, y=df2.Value)
trace2 = go.Scatter(x=df3.Date, y=df3.Value)
                                                      
fig.add_trace(trace1, row=1, col=1)
fig.add_trace(trace2, row=2, col=1)
fig.update_yaxes(fixedrange=True)
fig.update_layout(xaxis1_showticklabels=True, xaxis2_showticklabels=True)

fig.show()
fig2.show()

Which yields three plots.这产生了三个地块。 The two scatter plots in the subplot are aligned, the third gantt plot isn't.子图中的两个散点图是对齐的,第三个甘特图 plot 不是。

在此处输入图像描述

Ideally, I would like to add the gantt plot to the subplot with another add_trace command specifying col3, row1.理想情况下,我想使用另一个指定 col3、row1 的 add_trace 命令将甘特图 plot 添加到子图中。 I have been unable to do that successfully so far.到目前为止,我一直无法成功地做到这一点。 If I can't add the gantt plot to the subplot, I would like to align the x-axis' so they are the same width and the dates align vertically.如果我不能将甘特图 plot 添加到子图中,我想对齐 x 轴,以便它们具有相同的宽度并且日期垂直对齐。

If I add the gantt plot to the subplot like this如果我像这样将甘特图 plot 添加到子图中

fig.add_trace(fig2.data[0], row=3, col=1)

The plot is displayed incorrectly, as shown below. plot显示错误,如下图。

在此处输入图像描述

I believe that add_trace is not correctly interpreting the base and x fields of the fig2.data shown below.我相信 add_trace 没有正确解释下面所示的 fig2.data 的 base 和 x 字段。 Instead of adding the units in the x field to the dates in base, it is plotting them as numerical.它不是将 x 字段中的单位添加到 base 中的日期,而是将它们绘制为数字。

(Bar({
    'alignmentgroup': 'True',
    'base': array([datetime.datetime(2009, 1, 1, 0, 0),
                   datetime.datetime(2009, 3, 5, 0, 0)], dtype=object),
    'hovertemplate': 'Resource=Alex<br>Start=%{base}<br>Finish=%{x}<br>Task=%{y}<extra></extra>',
    'legendgroup': 'Alex',
    'marker': {'color': '#636efa'},
    'name': 'Alex',
    'offsetgroup': 'Alex',
    'orientation': 'h',
    'showlegend': True,
    'textposition': 'auto',
    'x': array([5.0112e+09, 3.5424e+09]),
    'xaxis': 'x',
    'y': array(['Job A', 'Job B'], dtype=object),
    'yaxis': 'y'
})
  • you have not provided sample data, so have simulated.你没有提供样本数据,所以模拟了。 Assumed y values of scatter are different to y values of gantt假设散点图的 y 值与甘特图的 y 值不同
  • simple case of adding scatter to figure and configuring axes appropriately向图形添加点并适当配置轴的简单案例
import plotly.express as px
import pandas as pd
import numpy as np

df = pd.DataFrame(
    [
        dict(Task="Job A", Start="2009-01-01", Finish="2009-02-28", Resource="Alex"),
        dict(Task="Job B", Start="2009-03-05", Finish="2009-04-15", Resource="Alex"),
        dict(Task="Job C", Start="2009-02-20", Finish="2009-05-30", Resource="Max"),
    ]
)
df["Start"] = pd.to_datetime(df["Start"])
df["Finish"] = pd.to_datetime(df["Finish"])


fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Resource")
fig.update_yaxes(autorange="reversed")

df2 = pd.DataFrame(
    {
        "Date": pd.date_range(
            df.loc[:, ["Start", "Finish"]].values.min(),
            df.loc[:, ["Start", "Finish"]].values.max(),
            freq="W-MON",
        )
    }
).pipe(lambda d: d.assign(Value=np.random.randint(1, 20, len(d))))

fig.add_traces(
    px.scatter(df2, x="Date", y="Value").update_traces(yaxis="y2").data
).update_layout(
    yaxis2={"overlaying": "y", "side": "right"}, xaxis={"domain": [0, 0.98]}
)

在此处输入图像描述

The way to do this is to pass the gantt figure to make_subplots as a parameter.这样做的方法是将甘特图作为参数传递给 make_subplots。

import plotly.express as px
import pandas as pd
import numpy as np
from plotly.subplots import make_subplots
import plotly.graph_objects as go

df = pd.DataFrame(
    [
        dict(Task="Job A", Start="2009-01-01", Finish="2009-02-28", Resource="Alex"),
        dict(Task="Job B", Start="2009-03-05", Finish="2009-04-15", Resource="Alex"),
        dict(Task="Job C", Start="2009-02-20", Finish="2009-05-30", Resource="Max"),
    ]
)
df["Start"] = pd.to_datetime(df["Start"])
df["Finish"] = pd.to_datetime(df["Finish"])


fig2 = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Resource")

df2 = pd.DataFrame(
    {
        "Date": pd.date_range(
            df.loc[:, ["Start", "Finish"]].values.min(),
            df.loc[:, ["Start", "Finish"]].values.max(),
            freq="W-MON",
        )
    }
).pipe(lambda d: d.assign(Value=np.random.randint(1, 20, len(d))))

df3 = pd.DataFrame(
    {
        "Date": pd.date_range(
            df.loc[:, ["Start", "Finish"]].values.min(),
            df.loc[:, ["Start", "Finish"]].values.max(),
            freq="W-MON",
        )
    }
).pipe(lambda d: d.assign(Value=np.random.randint(1, 20, len(d))))
trace1 = go.Scatter(x=df2.Date, y=df2.Value)
trace2 = go.Scatter(x=df3.Date, y=df3.Value)


fig = make_subplots(rows=3, cols=1, figure=fig2, shared_xaxes=True)
fig.add_trace(trace1, row=2, col=1)
fig.add_trace(trace2, row=3, col=1)
fig.update_layout(xaxis1_showticklabels=True, xaxis2_showticklabels=True, xaxis3_showticklabels=True)
fig.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Plotly add_trace go.scatter for-loop 填充 plot 图例 - Populating plot legend with only unique trace names with Plotly add_trace go.scatter for-loop Plot 使用 go.Scatter() 与整个 dataframe - Plot using go.Scatter() with entire dataframe Plotly:如何使用 DASH 回调将多项式拟合线添加到 plotly go.scatter 图? - Plotly: How to add polynomial fit line to plotly go.scatter figure using a DASH callback? Plotly:如何将元参数用于 go.Scatter 等函数? - Plotly: How to utilize meta argument for functions such as go.Scatter? Plotly 带有 px.imshow 和 go.Scatter 的动画子图 - Plotly animated subplots with px.imshow and go.Scatter Plotly px.Scatter 或 go.Scatter Graph 特定点的唯一颜色/符号(简单地图) - Plotly px.Scatter or go.Scatter Graph Unique Color/Symbol for specific points (Simple Map) Plotly:如何使用 go.Figure 和 go.Scatter 为每个 y 误差条设置单独的颜色? - Plotly: How to set individual color for each y error bar using go.Figure and go.Scatter? plotly:添加框 plot 作为子图 - plotly: add box plot as subplot 了解matplotlib中subplot和add_subplot(散点)图之间的区别 - Understanding the difference between subplot and add_subplot (scatter) plots in matplotlib 将附加图添加到子图 plotly python - Add additional plot to subplot plotly python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM