【问题标题】:Pandas dataframe Plotly line chart with two linesPandas 数据框用两条线绘制折线图
【发布时间】:2020-08-26 07:16:16
【问题描述】:

我有一个如下的 pandas 数据框,我想用这些数据制作一些图表。 'Name'列是账号名称,'Number'列是每个count下的用户数,months列是每个月每个账号的登录次数。

Acc       User     Jan     Feb     Mar     Apr     May     June
Nora      39       5       13      16      22      14      20
Bianca    53       14      31      22      21      20      29
Anna      65       30      17      18      28      12      13
Katie     46       9       12      30      34      25      15
Melissa   29       29      12      30      10      4       9

1st:我想监测一月到五月的登录趋势。一行显示 Bianca 的登录,另一行显示其他所有人的登录。

2nd:我想监控从 1 月到 5 月登录的百分比变化。一行展示了 Bianca 的登录百分比变化,另一行展示了其他所有人的登录百分比变化。

感谢您的时间和帮助。我是这方面的初学者。我很感激这方面的任何帮助!非常感谢!

【问题讨论】:

  • 你已经尝试了什么?
  • 首先尝试操纵您的数据框以获取所需的值,如列表、熊猫系列等(→ 像 df.sum() 和 df.pct_change() 之类的东西应该可以完成这项工作。比有查看Line charts using plotly 以获得所需的可视化效果。

标签: python pandas graph charts plotly


【解决方案1】:

我建议最好的分组方法是使用分类。 pct_change 不是一个直接的聚合函数,所以获取它的过程有点复杂。

import io
import matplotlib.pyplot as plt

df = pd.read_csv(io.StringIO("""Acc       User     Jan     Feb     Mar     Apr     May     June
Nora      39       5       13      16      22      14      20
Bianca    53       14      31      22      21      20      29
Anna      65       30      17      18      28      12      13
Katie     46       9       12      30      34      25      15
Melissa   29       29      12      30      10      4       9"""), sep="\s+")

# just setup 2 plot areas
fig, ax = plt.subplots(1,2, figsize=[20,5])

# want to divide data into 2 groups
df["grp"] = pd.Categorical(df["Acc"], ["Bianca","Others"])
df["grp"].fillna("Others", inplace=True)
# just get it out of the way...
df.drop(columns="User", inplace=True)
# simple plot where function exists directly.  Not transform to get lines..
df.groupby("grp").sum().T.plot(ax=ax[0])
# a bit more sophisticated to get pct change...
df.groupby("grp").sum().T.assign(
         Bianca=lambda x: x["Bianca"].pct_change().fillna(0)*100,
         Others=lambda x: x["Others"].pct_change().fillna(0)*100
     ).plot(ax=ax[1])

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2018-03-19
    • 2018-07-28
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多