Multiple Y-Axes

Multiple Y-Axes#

Goal

Demonstrate how to create a Plotly chart with two y-axes to display variables with different units on the same time axis. Temperature is shown on the left y-axis and relative humidity on the right y-axis.

Data Basis

The dataset flatTempHum.csv contains hourly indoor temperature and humidity measurements (columns: time, FlatA_Hum, FlatA_Temp, …; separator ;). We plot FlatA_Temp and FlatA_Hum on separate y-axes.

Data Preparation#

import pandas as pd

url = "https://raw.githubusercontent.com/retomarek/edap/main/edap/sampleData/flatTempHum.csv"
raw = pd.read_csv(url, sep=";")

# Parse timestamp and set as index
raw["time"] = pd.to_datetime(raw["time"])
raw = raw.set_index("time")

# Select FlatA columns
df = raw[["FlatA_Temp", "FlatA_Hum"]].dropna()

df.head()
FlatA_Temp FlatA_Hum
time
2018-10-03 00:00:00 24.43 53.0
2018-10-03 01:00:00 24.40 53.0
2018-10-03 02:00:00 24.40 53.0
2018-10-03 03:00:00 24.40 53.0
2018-10-03 04:00:00 24.40 53.3

Visualization#

import plotly.graph_objects as go
from plotly.subplots import make_subplots

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

# Temperature on primary (left) y-axis
fig.add_trace(
    go.Scatter(x=df.index, y=df["FlatA_Temp"], name="Temperature", line=dict(color="#EF553B")),
    secondary_y=False,
)

# Humidity on secondary (right) y-axis
fig.add_trace(
    go.Scatter(x=df.index, y=df["FlatA_Hum"], name="Humidity", line=dict(color="#636EFA")),
    secondary_y=True,
)

fig.update_layout(
    title="FlatA — Temperature & Humidity",
    template="plotly_white",
)
fig.update_xaxes(title_text="Time")
fig.update_yaxes(title_text="Temperature [°C]", secondary_y=False)
fig.update_yaxes(title_text="Relative Humidity [%]", secondary_y=True)

fig.show()
Customization

You can add more traces or customize colors. To add a third y-axis, use make_subplots with additional specs.

# Add another flat's temperature
fig.add_trace(
    go.Scatter(x=raw.index, y=raw["FlatB_Temp"], name="FlatB Temp", line=dict(dash="dash")),
    secondary_y=False,
)