使用 plotly 库的队列图

Cohort Chart using plotly library

我有一个数据集(CSV 文件),我想使用 plotly 库构建队列分析图表。可能吗?因为我看不到任何教程

  • 根据我在评论中的问题同类群组图表不是一种图表类型,而是一种分析方法
  • 出于此分析的目的,我通过仅考虑月份开始减少了日期的维度
  • 同类群组分析的第一部分是将您的数据放入同类群组中。最常见的方法似乎是第一次观察客户。使用了来自 InvoiceDate
  • Date
  • 下一部分现在是 activity 每个群组成为客户后的天数。再次使用 pandas 日期功能坚持月开始
  • 现在我们可以计算他们成为客户后按群组和月份计算的总支出
  • 将其重新设定为百分比,因为这似乎是一种方式同类群组分析总是有效
  • 现在简单一点 - 生成 plotly 热图

数据准备和绘图

import plotly.express as px

# just month, time doesn't matter
df["Date"] = pd.to_datetime(df["InvoiceDate"]).dt.date - pd.offsets.MonthBegin(1)
# work out when customer was first a customer to define which cohort
df2 = df.merge(
    df.groupby(["CustomerID"], as_index=False).agg(Cohort=("Date", "min")),
    on="CustomerID",
)
# months between cohort start and invoice date
df2["Month"] = df2["Date"].dt.to_period("M").view(dtype="int64") - df2[
    "Cohort"
].dt.to_period("M").view(dtype="int64")

df_cohort = (
    df2.groupby(["Cohort", "Month"])
    .apply(lambda d: (d["Quantity"] * d["UnitPrice"]).sum())
    .unstack("Month")
)

# rebase as percentage as per referenced example
for c in df_cohort.columns[1:]:
    df_cohort[c] = df_cohort[c] / df_cohort[0]
df_cohort[0] = 1

# now the easy bit - generate a figure
px.imshow(
    df_cohort, text_auto=".2%", color_continuous_scale="blues", range_color=[0, 1]
).update_xaxes(side="top", dtick=1).update_yaxes(dtick="M1")

数据来源

import kaggle.cli
import sys
import pandas as pd
from zipfile import ZipFile
from pathlib import Path
import urllib
import plotly.graph_objects as go

# fmt: off
# download data set
url = "https://www.kaggle.com/datasets/carrie1/ecommerce-data"
ds = urllib.parse.urlparse(url).path[1:]
try:
    sys.argv = [sys.argv[0]] + f"datasets download {ds}".split(" ")
    kaggle.cli.main()
except NameError:
    ds = "/".join(ds.split("/")[1:])
    sys.argv = [sys.argv[0]] + f"datasets download {ds}".split(" ")
    kaggle.cli.main()
    
zfile = ZipFile(list(Path.cwd().glob(f"{ds.split('/')[-1]}*.zip"))[0])
dfs = {f.filename: pd.read_csv(zfile.open(f), encoding= 'unicode_escape') for f in zfile.infolist()}
# fmt: on
df = dfs["data.csv"]