0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rで来店顧客の多い時間を週ごとに分析(ggplot+facet_grid使用)

Posted at

はじめに

Rを使って、時間帯ごとの来店数を、週ごとに別の棒グラフで分析する方法を記録したいと思います。

対象データ

service.csv
cancel,weekday,hour,attention,sex,age
0,2,18,0,2,10
0,5,12,0,1,10
0,4,17,0,2,10
0,0,10,0,1,10
0,4,17,0,2,10
1,0,17,0,1,10
-------

左から→キャンセルフラグ,曜日,時間,注意フラグ,性別,年代
となります。
(注意フラグは、一定のキャンセル数以上の場合に1が入ります)
こんな感じのcsvデータを利用します。

結果グラフ

image.png
※木曜、土曜は午前のみ営業
※14時台は来店が少なく、他は週ごとに多い時間帯が変化している様子

コード

# モジュールのロード
library(ggplot2)
library(dplyr)

# csvの読み込み(先頭行をヘッダに。ファイル文字コードはUTF-8。セパレータは,)
# パラメータをきちんと明示した方が安定する
# encoding="UTF-8"とfileEncoding="UTF-8"は違うので注意
df <- read.csv("service.csv", header = TRUE, fileEncoding="UTF-8", stringsAsFactors = FALSE, sep = ",")

# 週と時間それぞれでgoroupする(dplyrの機能)
df <- group_by(df, weekday, hour)

# group対象の行数をカウントしてcountというカラムを追加(dplyrの機能)
df <- summarize(df, count=n())

# arrangeを使ってweekdayの昇順で並び替え(dplyrの機能)
df <- arrange(df, weekday)

# 先頭行を出力
head(df)

##  Source: local data frame [6 x 3]
##  Groups: weekday [1]
##  
##    weekday  hour count
##      <int> <int> <int>
##  1       0    10    37
##  2       0    11    29
##  3       0    12    35
##  4       0    14    21
##  5       0    15    35
##  6       0    16    37

# 週のレベルを設定
custom_label <- as_labeller(c("0"="月", "1"="火", "2"="水", "3"="木", "4"="金", "5"="土"))

# plotを作成
gp <- ggplot(
  df,
  aes (
    x = hour,
    y = count,
    fill= hour
  )
) 
gp <- gp + geom_bar(stat = "identity")
gp <- gp + facet_grid(weekday ~ ., labeller = custom_label)  # facetgridで週ごとに表示
gp <- gp + ggtitle("週と時間による来店数の分析")
gp <- gp + scale_x_continuous(breaks=c(10, 11, 12, 13, 14, 15, 16, 17, 18)) # xの刻み
plot(gp)

まとめ

今回は来店顧客の時間ごとの分析を、集別にしてみました。
参考になりましたでしょうか。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?