2016-11-21 97 views
0

我想將相應的值標籤放置在每個條塊段中間的geom_col堆疊條形圖中。在geom_col堆疊條形圖中的每個條塊中間位置geom_text

但是,我的天真嘗試失敗。

library(ggplot2) # Version: ggplot2 2.2 

dta <- data.frame(group = c("A","A","A", 
          "B","B","B"), 
        sector = c("x","y","z", 
          "x","y","z"), 
        value = c(10,20,70, 
          30,20,50)) 

ggplot(data = dta) + 
    geom_col(aes(x = group, y = value, fill = sector)) + 
    geom_text(position="stack", 
      aes(x = group, y = value, label = value)) 

顯然,設置y=value/2geom_text沒有幫助,無論是。此外,文本的位置錯誤(顛倒)。

任何(優雅)的想法如何解決這個問題?

回答

4

您需要有一個映射到美學的變量來表示geom_text中的組。對你而言,這是你的「扇區」變量。您可以在geom_text中使用group美學。

然後用position_stackvjust來標記中心。

ggplot(data = dta) + 
    geom_col(aes(x = group, y = value, fill = sector)) + 
    geom_text(aes(x = group, y = value, label = value, group = sector), 
        position = position_stack(vjust = .5)) 

您可以通過在全球範圍內設置美學來保存一些打字。然後fill將用作geom_text的分組變量,您可以跳過group

ggplot(data = dta, aes(x = group, y = value, fill = sector)) + 
    geom_col() + 
    geom_text(aes(label = value), 
       position = position_stack(vjust = .5)) 

enter image description here

相關問題