You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Plotly实现用户留存热力图?Seaborn转Plotly时DataFrame传参疑问

How to Recreate a Seaborn Retention Heatmap with Plotly Graph Objects Using a DataFrame

Got it, let's convert that Seaborn retention heatmap over to Plotly Graph Objects using your existing DataFrame—it's actually simpler than you might think! Here's how to replicate the exact same visual with interactive Plotly features:

import pandas as pd
import plotly.graph_objects as go

# Your original cohort retention DataFrame
df = pd.DataFrame(
    index=['01.2020','02.2020','03.2020','04.2020','05.2020','06.2020'],
    data={
        0:[1,1,1,1,1,1],
        1:[0.58, 0.88, 0.27, 0.28, 0.68,0.90],
        2:[0.56, 0.58, 0.1, 0.77, 0.68,None],
        3:[0.78, 0.33, 0.4, 0.79, None,None],
        4:[0.58, 0.16, 0.89, None, None,None],
        5:[0.25, 0.14, None, None, None,None],
        6:[0.69, None, None, None, None,None]
    }
)

# Build the Plotly heatmap
fig = go.Figure(data=go.Heatmap(
    z=df.values,  # Pass the DataFrame's numeric values as the heatmap core data
    x=df.columns,  # Use columns for retention period (x-axis)
    y=df.index,    # Use index for cohort months (y-axis)
    # Format values as percentages for annotations, handle nulls
    text=df.applymap(lambda x: f"{x:.0%}" if pd.notnull(x) else ""),
    texttemplate="%{text}",  # Display the formatted text on the heatmap
    textfont={"size": 12},
    colorscale="Blues",  # Match Seaborn's default blue color scheme
    hoverongaps=False    # Skip hover tooltips for null values
))

# Adjust layout to match Seaborn's appearance
fig.update_layout(
    title="Cohorts: User Retention",
    xaxis_title="Retention Period",
    yaxis_title="Cohort Month",
    width=1200,
    height=800,
    yaxis_autorange="reversed"  # Reverse y-axis so first cohort is at the top (like Seaborn)
)

# Show the interactive plot
fig.show()

Key Details to Note:

  • Passing the DataFrame: We use df.values to feed the numeric matrix into Plotly's z parameter, which is what the heatmap uses to color cells. x and y directly map to your DataFrame's columns and index, so no extra reshaping is needed.
  • Annotations: The text and texttemplate parameters replicate Seaborn's annot=True, fmt='.0%'—we format each value as a percentage and leave null cells blank.
  • Layout Match: Setting yaxis_autorange="reversed" ensures your cohort months are ordered from top to bottom just like in the Seaborn plot, and we use a blue colorscale to mirror the default Seaborn look.
  • Interactivity: Unlike Seaborn, this Plotly heatmap will let you hover over cells for clearer value visibility, zoom, and pan—nice bonus features!

内容的提问来源于stack exchange,提问作者Thistle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:58:11