2016-10-25 14 views
1

これはサンプルデータである(より効率的にサンプルデータを作成する方法上の任意のヒント?)複数の条件と比較するためにデータを視覚化する方法は? ggplot2、R、geom_bar()

# sample data 

    city = c("paris", "tokyo", "seoul", "shanghai", "rome", "berlin", 
      "paris", "tokyo", "seoul", "shanghai", "rome", "berlin", 
      "paris", "tokyo", "seoul", "shanghai", "rome", "berlin", 
      "paris", "tokyo", "seoul", "shanghai", "rome", "berlin") 
    week = c(41,41,41,41,41,41, 
      42,42,42,42,42,42, 
      41,41,41,41,41,41, 
      42,42,42,42,42,42) 
    type = c("A","A","A","A","A","A", 
      "B","B","B","B","B","B", 
      "C","C","C","C","C","C", 
      "A","B","C","A","B","C") 
    count = sample(1:100, 24, replace = F) 

df = data.frame(city,count,week,type) 
df <- data.table(df) 
df[, .(count=sum(count)), by =.(city,type, week)] 

これは私が最初に作成したグラフです。

# graph 1 
ggplotly(
     ggplot(df, aes(reorder(city,-count), count)) + 
       geom_bar(stat="identity", aes(color=type, fill=type)) + 
       scale_y_continuous(labels = comma) + 
       theme(axis.text.x = element_text(angle= 90, hjust=1), 
         legend.position= "bottom")+ 
       guides(fill=FALSE)+ 
       coord_flip()+ 
       facet_grid(~week) 
) 

enter image description here

私は基本的に、週によって都市あたりのカウント数を比較したい と比較するための「かわす」を使用して、それを再構築したいです。

enter image description here

^^^そのようなことは 、素晴らしいことだが、バーでは、週によって種類やそのグループに分解「スタック」タイプでなければなりません。

ここに私が試したグラフがあります。今

# graph2 

position = position_dodge(width = .75) 
width = .65 
ggplotly(
     ggplot(df, aes(x = city, y = count, label = count, fill = type, group = week)) + 
       geom_bar(width = width, stat='identity', position = position) + 
       geom_text(hjust = -0.5, size = 3, position = position) + 
       coord_flip() 
) 

enter image description here

、これがすべてでは本当に醜いと分かりません見えます。

私の質問は、週を区別して、種類を分類してカウントをラベリングしながら週別の違いを比較する方法です。

+0

R http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-に大きなreproductible例を作成する方法についての興味深いリンク例 – Romain

+0

「ローマ」は、「B」カテゴリ(行11)で42週目のカウント27、**同じ**週(42)および**同じ**カテゴリ(「B」、行23)で55です。それは慎重ですか?彼らは集計されるべきではありませんか? – jakub

答えて

1

Tidyverseへようこそ!

interactionを使用して、weekcityをグループ化することができます。伝説は再加工する必要がありますが、あなたが得たいもののように見えます。

library(tidyverse) 

df <- tibble(week, city, type, count) 

df %>% 
    group_by(city, week, type) %>% 
    summarise(count = sum(count)) %>% 
    ggplot() + 
    geom_bar(aes(x = interaction(week, city), y = count, fill = type), 
      stat = "identity") 

enter image description here

関連する問題