【问题标题】:Plotting line plot with groupby in matplotlib/seaborn?在 matplotlib/seaborn 中使用 groupby 绘制线图?
【发布时间】:2017-11-24 18:12:52
【问题描述】:

我有以下数据集(缩写,但仍传达相同的想法)。我想展示用户分数如何随时间变化(postDate 传达时间)。数据也由@​​987654321@ 预排序。希望看到一个漂亮的图(如果可能,可能使用 seaborn),它的 y 轴为分数,x 轴为时间,并显示用户随时间的分数(每个用户有一条单独的线)。我是否需要将postDate(当前为字符串)转换为另一种格式才能很好地绘制?非常感谢!

userID   postDate                                userScore (1-10 scale)
Mia1     2017-01-11 09:07:10.616328+00:00        8
John2    2017-01-17 08:05:45.917629+00:00        6
Leila1   2017-01-22 07:47:67.615628+00:00        9
Mia1     2017-01-30 03:45:50.817325+00:00        7
Leila    2017-02-02 06:38:01.517223+00:00        10

【问题讨论】:

  • groupby 是从哪里来的?你想为每个用户写一行吗?
  • 是的,groupby 对每个用户来说都是一个单独的行(并且有很多用户——有些用户有 20 个或更多帖子)。也可能有其他方法可以做到这一点,我只是想 groupby 可能是必要的。
  • 会是这样的:df.pipe(seaborn.FacetGrid, hue='userID').map(plt.plot, 'postDate', 'userScore')

标签: python pandas plot seaborn pandas-groupby


【解决方案1】:

根据您显示的示例数据,您的 postDate 系列已经是 pandas 日期时间值。因此,要在 X 轴上绘制日期,matplotlib 中的关键是使用plot_date,而不是绘图。像这样的:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

for key, g in df.groupby['userID']:
    ax.plot_date(g['postDate'], g['userScore'], label=key)

ax.legend()

【讨论】:

    【解决方案2】:

    我之前使用过plotly,如果您使用的是 Jupyter Notebook,它是进行交互式可视化的一个非常好的选择。您可以使用袖扣在 Jupyter 中生成 htmls 或内联绘图。它只是为在某处托管您的图表而付费,但我免费使用它来进行我自己的数据分析。

    安装 plotly 和袖扣,袖扣有助于使用 pandas dfs 几乎立即进行绘图。

    例如你可以这样做:

    your_df.iplot(x='postDate', y='userScore')
    

    这将自动为您提供您描述的“时间序列”。

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2019-10-21
      • 2019-07-13
      • 2017-08-10
      • 2021-05-12
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      相关资源
      最近更新 更多