Plotly:将数组传递给 'fillcolor' 参数

Plotly: Pass array to 'fillcolor' argument

我正在尝试将一组颜色传递给 'fillcolor' 参数,以便有条件地为图表下方的区域着色。

首先,将带有颜色或 rgba 代码的字符串传递给 'fillcolor' 参数效果很好:

fig.add_trace(
        go.Scatter(x=x,
                   y=y,
                   mode='lines',
                   fill='tozeroy',
                   fillcolor='red',
                   line=dict(color='rgba(255, 0, 0, 0.9)')))

向'fillcolor'参数传递数组时,如

fig.add_trace(
  go.Scatter(x=x,
             y=y,
             name='price',
             mode='lines',
             fill='tozeroy',
             fillcolor=np.where(y > -5, 'green', 'red'),
             line=dict(color='rgba(255, 0, 0, 0.9)')))

导致此错误:

ValueError: 
    Invalid value of type 'numpy.ndarray' received for the 'fillcolor' property of scatter

另外,直接传数组或者传'fillcolor=dict(color=array)'都不行。

是否有机会传递颜色数组,从而有条件地将区域填充到轴?

提前致谢!

  • 根据评论 fillcolor 不是数组 - 它是跟踪的一个属性
  • 要获得多色图形,您需要为图形中所需的每条颜色线(填充线)绘制轨迹
  • 在此解决方案中使用了 pandasPlotly Express,使用您的原始代码进行设置
  • 由于 tozeroy 的工作方式
  • ,这确实给出了略微不同的形状图
import numpy as np
import plotly.graph_objects as go

x = np.linspace(0, 20, 100)
y = np.random.randint(-7, 3, 100)
fig = go.Figure()
fig.add_trace(
    go.Scatter(
        x=x,
        y=y,
        mode="lines",
        fill="tozeroy",
        fillcolor="red",
        line=dict(color="rgba(255, 0, 0, 0.9)"),
    )
)
fig.show()

# create a dataframe to simplify solution.  green and red lines logic as additional columns
df = pd.DataFrame({"x": x, "y": y})
df = df.assign(
    y_green=np.where(df["y"] > -5, df["y"], 0), y_red=np.where(df["y"] > -5, 0, df["y"])
)

# create the plot
fig = px.line(
    df, x="x", y=["y_green", "y_red"], color_discrete_sequence=["green", "red"]
).for_each_trace(lambda t: t.update(fillcolor=t.line.color, fill="tozeroy"))

fig