【问题标题】:Pandas histogram bins alignment熊猫直方图箱对齐
【发布时间】:2019-04-17 19:20:42
【问题描述】:

我有一个如下所示的数据框:

train_data_10users = pd.DataFrame({'target':['A','A','B', 'B', 'C'], 'day_of_week':[4,2,4,4,1]})

 target  day_of_week
0   A            4
1   A            2
2   B            4
3   B            4
4   C            1

我想为每个目标按 day_of_week 计算计数直方图,即

"A" should have:
0,1,3,5,6:0
2,4:1
"B" should have
0,1,2,3,5,6:0
4:2
"C" should have 1:1, the rest:0

这是显示我希望在直方图上显示的真实数据的数据透视表(注意:fillna):

pivot = pd.pivot_table(train_data_10users,
                       index=["target"], columns=["day_of_week"], aggfunc='size', fill_value=0)

day_of_week 0   1   2   3   4   5   6
target                          
Ashley  390 328 1078    293 115 0   0
Avril   148 402 273 318 87  104 311
Bill    308 239 105 24  54  7   65
Bob 51  285 72  284 330 0   0

即使 groupby 中可能缺少某些天,添加适当的 xticks 也可以解决问题:

from matplotlib import pyplot as plt
import pandas as pd

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(16, 10))
for idx, (user, sub_df) in enumerate(
        pd.groupby(train_data_10users[["target", "day_of_week"]], 'target')): 
    ax = axes[idx // 4, idx % 4]
    sub_df.hist(ax=ax, label=user, color=color_dic.get(user), bins=7)
    ax.set_xticks(range(7))
    ax.legend()

但是这些值并没有完全对齐/居中,而且位置有点浮动,我认为这取决于每个目标存在/缺失的天数:

更新。 这是根据接受的答案的外观:

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(16, 10), sharey=True)
...
sub_df.hist(ax=ax, label=user, color=color_dic.get(user), bins=range(8))
ax.set_xticks(range(8))
ax.set_xticks(np.arange(8)+0.5)
ax.set_xticklabels(range(7))

【问题讨论】:

  • 什么是train_data_10usersaxes 是什么?
  • 这是我的数据框和子图轴
  • 对于那些试图重新创建数据框的人:train_data_10users = pd.DataFrame({'target':['A','A','B', 'B', 'C'], 'day_of_week':[4,2,4,4,1]})
  • 那么你期望什么,从 hist bin 中删除那些零/NaN 的?这不是真正的直方图。
  • 如果符合您的需要,请查看我编辑的答案。

标签: python pandas dataframe histogram


【解决方案1】:

试试:

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(16, 10))
for idx, (user, sub_df) in enumerate(
    pd.groupby(train_data_10users[["target", "day_of_week"]], 'target')): 
    ax = axes[idx // 4, idx % 4]

    # note bin is forced to range(7)
    sub_df.hist(ax=ax, label=user, bins=range(7))

    # offset the xticks
    ax.set_xticks(np.arange(7) + .5)

    # name the label accordingly
    ax.set_xticklabels(range(7))

bins=range(7) 的输出:

【讨论】:

  • 请注意,我还将bins 更改为range(7)。它与bins=7 有点不同,因为bins=7min-max 划分为7 个bin,而正式将其专门设置为(0,1,2,3,4,5,6)
  • 是的,我注意到了这一点并删除了我的上一条评论。不过还是有一点小问题。现在,hist 有点向右筛选,第一天没有价值。让我将图片发布为 Upd。
  • 将偏移量更改为 `+0.5``。
  • 我试过了,但它恰恰相反,+0.5 它不会显示最后一天的值..
  • 发现问题,换bins=range(8)。另外,考虑将sharey=True 放到subplots
猜你喜欢
  • 2016-01-24
  • 1970-01-01
  • 2018-07-05
  • 2018-12-05
  • 1970-01-01
  • 2017-09-24
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多