簡體   English   中英

在堆積條形圖中過濾geom_text值標簽

[英]Filter geom_text value labels in a stacked bar chart

我想創建一個帶有ggplot的堆積條形圖,並為其添加(居中)標簽:當值太低時,我不想顯示標簽。

df<-data.frame(x=unlist(strsplit("AAAABBBB","")),
           z=unlist(strsplit("ABCDABCD","")),
           y=c(40,5,30,10,50,60,5, 40))

# this works fine
library(ggplot2)
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") + 
   geom_text(data  = df, aes(x=x, y=y, label = y), position = position_stack(vjust=0.5))

在此輸入圖像描述

但是當我過濾這樣的值(見下文)時,它也會改變每個標簽的定位。 這適用於散點圖,但由於定位基於堆疊值,因此標簽顯示得太低。

#don't show values 5 or less
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") + 
    geom_text(data = df[df$y > 5,], aes(x=x, y=y, label = y), position = 
    position_stack(vjust=0.5)) 

在此輸入圖像描述

我們可以創建一個值'y1',其值小於或等於5為空( "" )並在label參數中使用它

df %>% 
     mutate(y1 = replace(y, y<=5, ""))

p2 <- ggplot(df, aes(x=x, y=y, fill = z)) + 
         geom_bar(stat="identity") + 
         geom_text(data  = df, aes(x=x, y=y, label = y1),
                  position = position_stack(vjust=0.5))
p2

在此輸入圖像描述


通過與OP的帖子中的第一個圖比較來檢查位置

p1 <- ggplot(df, aes(x=x, y=y, fill = z)) + 
                  geom_bar(stat="identity") +
                  geom_text(data  = df, aes(x=x, y=y, label = y), 
                      position = position_stack(vjust=0.5))

library(ggpubr)
ggarrange(p1, p2, ncol =2, nrow = 1, labels = c("p1", "p2"))

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM