Quantcast
Viewing all articles
Browse latest Browse all 123

ggplot2 で内訳を左から右に詳細化していく棒グラフ

ggplot2 でラザニアプロット(ある値以上の値を合算したヒートマップ) - 廿TTに引き続き、新しい geom を作ってみたくて geom_drilldown.R · GitHubを書きました。

ggplot2 で内訳を左から右に詳細化していく棒グラフ(ツリーマップ?)です。

{googleAnalyticsR} {ggplot2} 内訳をドリルダウンしていく棒グラフ - 廿TTを関数化したものです。

内部で dplyr と tidyr を使っています。

最初はぜんぶ ggplot の中でやろうとしたけど、やっぱりむりがあると思いなおし、データの下処理は make_drilldown という別の関数に任せることにしました。

Googleアナリティクスのデータで試してみます。

library(googleAnalyticsR)library(ggplot2)source("https://gist.githubusercontent.com/abikoushi/09e1becbbe563ed873e5c6484ed92ec8/raw/758b851ba9aa5fd585bfdeefbd33999f1767ea24/geom_drilldown.R")

ga_auth()
account_list <- ga_account_list()
ga_id <- account_list[3,'viewId']

CVfilter <- 
  filter_clause_ga4(list(met_filter("goal3Completions","GREATER_THAN","0")))
dims <-c("userType","channelGrouping","deviceCategory")
mets <-c("goal3Completions","sessions")
gadata <-
  google_analytics_4(ga_id,
                     date_range = c("2017-05-01","2017-05-31"),
                     metrics = mets,
                     met_filters = CVfilter,
                     dimensions = dims,
                     max =20000)

dat_drill <-make_drilldown(gadata,dims,mets)#例1
ggplot(dat_drill,aes(x=dimensions,y=goal3Completions))+
  geom_drilldown(colour="black")+
  geom_drilldown_text(aes(label=label),colour="white")#例2
ggplot(dat_drill,aes(x=dimensions,y=goal3Completions,group=level))+
  geom_drilldown(aes(fill=label),alpha=0.3)+
  geom_drilldown_label(aes(label=label,fill=label))+
  theme(legend.position ="none")#例3
ggplot(dat_drill,aes(x=dimensions,y=goal3Completions))+
  geom_drilldown(aes(fill=goal3Completions/sessions))+
  geom_drilldown_text(aes(label=label))+
  scale_fill_continuous(low="white",high="cornflowerblue")+
  theme(legend.position ="bottom")

例1
Image may be NSFW.
Clik here to view.
f:id:abrahamcow:20170606001048p:plain

例2
Image may be NSFW.
Clik here to view.
f:id:abrahamcow:20170606001055p:plain

例3
Image may be NSFW.
Clik here to view.
f:id:abrahamcow:20170606001101p:plain

引っ張ってきたもとのデータ(gadata)はこんな形です。

"userType","channelGrouping","deviceCategory","goal3Completions","sessions"
"New Visitor","Direct","desktop",3,274
"New Visitor","Direct","mobile",1,560
"New Visitor","Organic Search","desktop",19,5256
"New Visitor","Organic Search","mobile",17,4353
"New Visitor","Organic Search","tablet",2,332
"New Visitor","Social","desktop",1,87
"New Visitor","Social","mobile",2,190
"Returning Visitor","Direct","desktop",4,98
"Returning Visitor","Direct","mobile",2,145
"Returning Visitor","Direct","tablet",1,14
"Returning Visitor","Organic Search","desktop",6,957
"Returning Visitor","Referral","desktop",5,87
"Returning Visitor","Social","desktop",3,119

試してみたい方がいたらご利用ください。

アマゾンアフィリエイトのコーナー

Image may be NSFW.
Clik here to view.
Rグラフィックスクックブック ―ggplot2によるグラフ作成のレシピ集

Rグラフィックスクックブック ―ggplot2によるグラフ作成のレシピ集


Viewing all articles
Browse latest Browse all 123

Trending Articles