2017-11-20 10 views
1

私は、site、purchase、およびhappycustomerという3つのカテゴリ変数を持つデータフレーム(df)を持っています。dplyr()とggolot2():: geom_tile、集計統計情報のグループ

私はgglot2のgeom_tile関数を使用して、顧客体験のヒートマップを作成したいと考えています。私はx軸上のサイト、y軸上の購入、そして充満としてのhappycustomerを望みます。私はヒートマップに、サイトと購入(つまり、happycustomerの価値がyのもの)でグループ分けされた幸せな顧客のパーセンテージを表示するようにしたいと思います。

私の問題は、現在、幸せな人と不幸な顧客の両方がいることです。

ご協力いただければ幸いです。

始点(DF):

df <- data.frame(site=c("GA","NY","BO","NY","BO","NY","BO","NY","BO","GA","NY","GA","NY","NY","NY"),purchase=c("a1","a2","a1","a1","a3","a1","a1","a3","a1","a2","a1","a2","a1","a2","a1"),happycustomer=c("n","y","n","y","y","y","n","y","n","y","y","y","n","y","n")) 

現在コード:ここ

library(ggplot2) 
library(dplyr) 
df %>% 
     group_by(site, purchase,happycustomer) %>% 
     summarize(bin = sum(happycustomer==happycustomer)) %>% 
     group_by(site,happycustomer) %>% 
     mutate(bin_per = (bin/sum(bin)*100)) %>% 
     ggplot(aes(site,purchase)) + geom_tile(aes(fill = bin_per),colour = "white") + geom_text(aes(label = round(bin_per, 1))) + 
     scale_fill_gradient(low = "blue", high = "red") 

答えて

0

は、2つのデータフレームを有する溶液です。

happyDF <- df %>% 
filter(happycustomer == "y") %>% 
group_by(site, purchase) %>% 
summarise(n = n()) 

totalDF <- df %>% 
group_by(site, purchase) %>% 
summarise(n = n()) 

そしてggplotコード:

merge(happyDF, totalDF, by=c("site", "purchase")) %>% 
mutate(prop = 100 * (n.x/n.y)) %>% 
ggplot(., aes(site, purchase)) + 
    geom_tile(aes(fill = prop),colour = "white") + 
    geom_text(aes(label = round(prop, 1))) + 
scale_fill_gradient(low = "blue", high = "red") 
関連する問題