如何在Python中像直方图一样绘制频率图

时间:2020-08-27 14:38:42

标签: python pandas matplotlib seaborn

我有一个频率表,如下所示:

  +---------------------------+------+
| timestamps                | freq |
+---------------------------+------+
| 2020-08-08 00:09:04+00:00 | 10   |
+---------------------------+------+
| 2020-08-08 00:21:51+00:00 | 3    |
+---------------------------+------+
| 2020-08-08 00:27:10+00:00 | 2    |
+---------------------------+------+

这是一个数据框。它包含大量这样的值。基本上,时间戳是相隔3分钟,每个时间戳都有一个频率。 24小时的总预期回收箱数为480。我需要像直方图或条形图那样绘制它们。到目前为止,我已经按小时获取了该信息。

df["date"] = df.timestamp.dt.date
df_temp = df.loc[df.date == pd.to_datetime("2020-08-18")]
df_temp["hours"] = df.timestamp.dt.hour

df_temp["hours"].plot.hist(grid=False, bins=24, rwidth=0.9,
                   color='#607c8e')
plt.title('Hourly Frequency')
plt.xlabel('Freq')
plt.ylabel('Hour')
plt.grid(axis='y', alpha=0.75)

这是输出 enter image description here

我对如何做到这一点感到很困惑?我尝试过使用seaborn

date = "2020-08-18"
bar = pd.DataFrame(columns=["timestamp", "freq"])
bar["timestamp"] = pd.date_range(str(date)+" 00:00:00+00:00", str(date)+" 22:59:00+00:00", freq="3min")
bar["min"] = bar.timestamp.dt.minute
freq["min"] = freq.timestamp.dt.minute
bar["freq"] = 0
freq_temp = freq.loc[freq.date == pd.to_datetime(date)]

for i in freq_temp.timestamp:
    for j in bar.timestamp:
      
        delta = math.ceil(abs(i-j).seconds/60)
  
        if(delta <= 3):
       
            v = bar.loc[pd.to_datetime(bar.timestamp) == pd.to_datetime(j) ,"freq"]
            v = freq.loc[pd.to_datetime(freq.timestamp) == pd.to_datetime(i) ,"freq"].to_string(index=False)
            bar.loc[pd.to_datetime(bar.timestamp) == pd.to_datetime(j) ,"freq"] = v
            break


plt.figure(figsize=(100, 50))
plt.title('Hourly Ad Frequency for day '+ str(date), fontsize=18)
g=sns.barplot(x='timestamp', y='freq', data=bar, hue='freq', dodge=False, ci=None)
g.legend().set_visible(False)
g.set_xlabel("Hour '(AM/PM)''",fontsize=16)
g.set_ylabel("freq",fontsize=16)

上面的代码正在创建另一个数据框栏。酒吧设有带有特定垃圾箱的时间戳,例如每3分钟间隔00:00 03:00 06:00。它从原始数据框中获取每个值,并在每个bin的3分钟内检查它是否喜欢。一旦找到一个频率,便为其分配该频率。这种方法非常慢。这是输出 m

当我将倒数第二个代码用于这样的时间戳时:

bar = freq.loc[freq.date == pd.to_datetime("2020-08-18")]
bar["hours"] = bar.timestamp.dt.hour

bar["timestamp"].plot.hist(grid=True, bins=24, rwidth=0.9,
                   color='#607c8e')
plt.title('Hourly Frequency')
plt.xlabel('Freq')
plt.ylabel('Hour')
plt.grid(axis='y', alpha=0.25)

它给了我这个错误: TypeError:数据类型无法理解

0 个答案:

没有答案
相关问题