【问题标题】:Changing line color based on other line's index根据其他行的索引更改行颜色
【发布时间】:2022-01-02 17:57:00
【问题描述】:

我有一个包含两列 Actual_ValuesPredicted_Valuesout 数据框。

我正在尝试创建图表:

import pandas as pd
import plotly.graph_objects as go

x_data = out.index

trace1 = go.Scatter(
    x=x_data,
    y=out['Actual_Values'],
    name="Actual Values"
)

trace2 = go.Scatter(
    x=x_data,
    y=out['Predicted_Values'],
    name="Predictions"
)

traces = [trace1, trace2]

layout = go.Layout(
    xaxis=dict(
        autorange=True
    ),
    yaxis=dict(
        autorange=True
    )
)

fig = go.Figure(data=traces, layout=layout)

plot(fig, include_plotlyjs=True)

给出:

但是,我需要一个图表,其中蓝线从红线开始变为其他颜色。

【问题讨论】:

标签: python plotly plotly-python


【解决方案1】:

这对你有帮助吗?

import pandas as pd
import numpy as np
import plotly.graph_objects as go

# Data
n = 150
n_pred = 10
df1 = pd.DataFrame(
    {"x": np.arange(n),
     "actual_value": np.random.randint(0, 100, n)})

df2 = pd.DataFrame(
    {"x": np.arange(n-n_pred, n),
     "predicted_value": np.random.randint(0, 100, n_pred)})

# You need Outer join when prediction range is
# larger than actual value one.
df = pd.merge(df1, df2, on="x", how="outer")


idx_min = df[df["predicted_value"].notnull()].index[0]

# Plot
trace1 = go.Scatter(
    x=df["x"][:idx_min+1],
    y=df['actual_value'][:idx_min+1],
    name="Actual Values",
    line=dict(color="blue")
)

trace2 = go.Scatter(
    x=df["x"][idx_min:],
    y=df['actual_value'][idx_min:],
    name="Actual Values",
    mode="lines",
    line=dict(color="green"),
    showlegend=False  
)

trace3 = go.Scatter(
    x=df["x"],
    y=df['predicted_value'],
    name="Predicted Values",
    line=dict(color="red")
)
traces = [trace1, trace2, trace3]

layout = go.Layout(
    xaxis=dict(
        autorange=True
    ),
    yaxis=dict(
        autorange=True
    )
)

fig = go.Figure(data=traces, layout=layout)
fig.show()

【讨论】:

    猜你喜欢
    • 2015-05-28
    • 1970-01-01
    • 2020-03-09
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2014-01-17
    • 2013-08-28
    相关资源
    最近更新 更多