使用 Plotly 在面积图上添加具有适当比例的线

Add a line with its proper scale on an area chart with Plotly

我有以下代码:

import pandas as pd
import plotly.express as px
fig = px.area(df, x="Decade", y="Financial_Impact", color="Disaster_Type", title="Financial Impact, World, RCP = 2.6", color_discrete_sequence=["#FDB714", "#009CA7", "#F05023"])
fig.show()

正在生成以下面积图:

现在我有一个名为 C 的变量,它提供每个十年的温度 (°C)。我如何添加一条显示 C 的线,其比例相对于图表右侧的 C

这是数据集的前五行:

df.head()

您将希望使用 graph_objects 而不是 Plotly express,使用 go.Scatterstackgroup 参数将数据添加为轨迹以创建重叠区域图,并创建辅助 y -轴。您可以为温度数据指定辅助 y 轴。我将创建一个与您类似的 DataFrame 来说明我的观点。

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

np.random.seed(42)
storm_data = np.repeat(3.5*10**9,21) + 10**8*np.random.normal(0,1,21)
flood_data = np.repeat(2*10**9,21) + 10**8*np.random.normal(0,1,21)
drought_data = np.repeat(1.4*10**9,21) + 10**8*np.random.normal(0,1,21)

df = pd.DataFrame({
    'Decade':np.linspace(1900,2100,21), 
    'Storms':storm_data, 
    'Floods':flood_data, 
    'Droughts':drought_data, 
    'Temperature':np.random.normal(30,10,21)
})

## create a secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])

## add your data using traces
fig.add_trace(go.Scatter(
    x=df.Decade,
    y=df.Storms,
    name='Storms',
    stackgroup='one'
))

fig.add_trace(go.Scatter(
    x=df.Decade,
    y=df.Floods,
    name='Floods',
    stackgroup='one'
))

fig.add_trace(go.Scatter(
    x=df.Decade,
    y=df.Droughts,
    name='Droughts',
    stackgroup='one'
))

## specify the secondary y_axis for temperature
fig.add_trace(go.Scatter(
    x=df.Decade,
    y=df.Temperature,
    name='Temperature',
    ),
    secondary_y=True
)

fig.show()

import plotly.express as px
from plotly.subplots import make_subplots

subfig = make_subplots(specs=[[{"secondary_y": True}]])

fig = px.area(df, x="Decade", y="Financial_Impact", color="Disaster_Type", color_discrete_sequence=["#FDB714", "#009CA7", "#F05023"])
fig2 = px.line(df, x="Decade",y=df.C)

fig2.update_traces(yaxis="y2",showlegend=True,name='Temperature')
subfig.add_traces(fig.data + fig2.data)

subfig.layout.xaxis.title="Decades"
subfig.layout.yaxis.title="Financial Impact"
subfig.layout.yaxis2.title="°C"
subfig.layout.title="Financial Impact, World, RCP = 2.6"

subfig.show()