2016-11-16 105 views
0

如何使用ggplot2繪製帶有計數標籤的「填充」條?在位置=「填充」的條形圖上繪製標籤g gplot2

我可以爲「堆疊」的酒吧做到這一點。但是我很困惑。

下面是使用dplyrMPG數據集重複的例子

library(ggplot) 
library(dplyr) 

mpg_summ <- mpg %>% 
    group_by(class, drv) %>% 
    summarise(freq = n()) %>% 
    ungroup() %>% 
    mutate(total = sum(freq), 
     prop = freq/total) 

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv)) 
g + geom_col(aes(fill = drv)) + 
    geom_text(aes(label = freq), position = position_stack(vjust = .5)) 

enter image description here

但是,如果我嘗試繪圖用於填充的條數不工作

g <- ggplot(mpg_summ, aes(x=class, fill=drv)) 
g + stat_count(aes(y = (..count..)/sum(..count..)), geom="bar", position="fill") + 
    scale_y_continuous(labels = percent_format()) 

enter image description here

而且,如果我嘗試:

g <- ggplot(mpg_summ, aes(x=class, fill=drv)) 
g + geom_bar(aes(y = freq), position="fill") + 
    geom_text(aes(label = freq), position = "fill") + 
    scale_y_continuous(labels = percent_format()) 

我得到:

Error: stat_count() must not be used with a y aesthetic. 

回答

2

我錯過了最後一個問題的填充部分。這應該讓你有:

library(ggplot2) 
library(dplyr) 

mpg_summ <- mpg %>% 
    group_by(class, drv) %>% 
    summarise(freq = n()) %>% 
    ungroup() %>% 
    mutate(total = sum(freq), 
     prop = freq/total) 

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv)) 
g + geom_col(aes(fill = drv), position = 'fill') + 
    geom_text(aes(label = freq), position = position_fill(vjust = .5)) 

enter image description here

+0

啊,這是很容易 - 非常感謝。 – val

+0

你會如何躲避標籤?如在哪裏我會把聲明position = position_dodge(width = 0.9)? – val

+0

我相信只有一個位置參數是允許的,所以'position_dodge'或'position_fill' –