2
votes

I have the following code:

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()

Generating the following area chart:

area chart

Now I have a variable called C providing a temperature (°C) for each decade. How could I add a line showing C, with a scale relative to C on the right of the chart?

Here are the first five rows of the dataset:

df.head()

dataset

2
Can you share your DataFrame so people can reproduce the output?Derek O

2 Answers

2
votes
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()

enter image description here

1
votes

You will want to use graph_objects instead of Plotly express, add your data as traces using go.Scatter and the stackgroup parameter to create overlapping area plots, and create a secondary y-axis. You can specify the secondary y-axis for your temperature data. I'll create a similar DataFrame as yours to illustrate my point.

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()

enter image description here