2015-04-15 66 views
1

我想正常化一個堆積圖,並把每個填充的中間填充的百分比。這是一個簡單的問題,但我沒有處理y值是什麼,因爲它是隱含的,所以我不知道如何設置:geom_text(aes(y=??, label=paste0(??,"%")))ggplot2:中等百分比的歸一化堆積圖

至於正常化,我已經看到人們預先崩潰並正常化dt,但我希望學習ggplot-ish的方式來做到這一點。

我是否需要將我的dt轉換爲time-grpmember百分比彙總表?這會讓我直接處理y值(例如,計算'每個填充的中間值')。

dt <- as.data.table(read.table(text = "time grpmember 
1 TRUE 
1 TRUE 
1 TRUE 
1 FALSE 
1 FALSE 
1 FALSE 
2 FALSE 
2 TRUE 
2 TRUE 
2 TRUE", header=TRUE)) 
dt$time <- as.factor(dt$time) 

ggplot(dt, aes(x=time)) + geom_bar(aes(fill=grpmember)) + geom_text(aes(y = 2, label=paste0("?", "%"))) 

Graph

+0

你能提供你計數的原始數據?如果我理解正確,那麼您會希望y軸以原始計數值表示,同時每個堆棧的百分比也顯示出來? –

+0

如果你想要一個100%疊加的條形圖,其中每個系列的百分比總和爲100%,ggplot2可以做到這一點,而不需要轉換數據:http://stackoverflow.com/questions/3619067/stacked -bar-chart-in-r-ggplot2 -y-axis-and-bars-as-percent-of-counts但是,就帶有這種圖表的百分比標籤而言,您可能需要隨時轉換爲彙總表提出並計算標籤的位置。 –

回答

1

編輯

從約ggplot 2.1.0,geom_text得到一個position_fill/position_stack,從而不再有必要計算,也不使用AY審美定位標籤(請參見原件下面的pos)。

dt <- read.table(text = "time grpmember 
1 TRUE 
1 TRUE 
1 TRUE 
1 FALSE 
1 FALSE 
1 FALSE 
2 FALSE 
2 TRUE 
2 TRUE 
2 TRUE", header=TRUE) 
dt$time <- as.factor(dt$time) 

library(ggplot2) 
library(dplyr) 

dtSummary = dt %>% 
    group_by(time, grpmember) %>% 
    summarise(count = n()) %>% 
    mutate(Percent = paste0(sprintf("%.1f", count/sum(count) * 100), "%")) 

ggplot(dtSummary, aes(x = time, y = count, fill = grpmember, label = Percent)) + 
    geom_bar(position = "stack", stat = "identity") + 
    geom_text(position = position_stack(vjust = .5)) 



原始

我不能完全確定你所追求的,但這種計算包含計數,標籤彙總表(即百分比)和位置的標籤(在每個片段的中點);然後繪製該圖。

dt <- read.table(text = "time grpmember 
1 TRUE 
1 TRUE 
1 TRUE 
1 FALSE 
1 FALSE 
1 FALSE 
2 FALSE 
2 TRUE 
2 TRUE 
2 TRUE", header=TRUE) 
dt$time <- as.factor(dt$time) 

library(ggplot2) 
library(dplyr) 

dtSummary = dt %>% 
# Get the counts 
    group_by(time, grpmember) %>% 
    summarise(count = n()) %>% 
# Get labels and position of labels 
    group_by(time) %>% 
    mutate(Percent = paste0(sprintf("%.1f", count/sum(count) * 100), "%")) %>% 
    mutate(pos = cumsum(count) - 0.5 * count)%>% 
    mutate(pos = cumsum(count) - 0.5 * count) %>% 
    mutate(grpmember = factor(grpmember), 
      grpmember = factor(grpmember, levels = rev(levels(grpmember)))) 

ggplot(dtSummary, aes(x = time, y = count, fill = grpmember)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(y = pos, label = Percent)) 

enter image description here

+0

這已經足夠接近了,儘管我用'data.table'重寫了'dplyr'命令。謝謝。 – rjturn

相關問題