Skip to content

Visualize 2D heatmap with marginal histogram

This template helps visualize the relationship between two variables as a 2-dimensional heatmap along with a histogram of the marginal distribution of the individual variables. Together, they allow one to derive important insights on the individual variables as well as the relationship between them.

# Load packages
import pandas as pd
import plotly.express as px
# Upload your data as csv and load as data frame
df = pd.read_csv('data/yellow_tripdata_2020-01_sampled.csv', parse_dates=['tpep_pickup_datetime'])
df['pickup_day'] = df['tpep_pickup_datetime'].dt.day_name()
df['pickup_time'] = df['tpep_pickup_datetime'].dt.hour
df.head()
# Visualize relationship as 2D heatmap with marginal histogram
DAYS_OF_WEEK = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
fig = px.density_heatmap(
    df.sample(frac = 0.1), 
    x="pickup_day", 
    y="pickup_time", 
    marginal_x="histogram", 
    marginal_y="histogram",
    color_continuous_scale = px.colors.sequential.Viridis,
    category_orders={"pickup_day": DAYS_OF_WEEK}
)
fig.show(config = {"displayModeBar": False})