2017-09-19 50 views
1

我是R中的新手,我想使用條形圖和ggplot將數據可視化。如何通過geom_bar將標籤放在R中的值爲負時

我有下面的數據,當我想要查看這些數據時,負值的文本不會顯示在Bar下面。

dat <- read.table(text = "sample Types Value 
sample1 A -36 
sample2 B 31 
sample1 C 15 
sample2 D -12 
sample1 E 27 
sample2 F 16 
sample2 G -10 
sample2 H 2 
sample2 I 6 
sample2 J -7 
sample2 K -8" 
, header=TRUE) 

library(ggplot2)  
px <- ggplot(data = dat , aes(x = Types , y = Value , Colour = Types)) 
px + geom_bar(stat = "identity" ,color = "#FFFFFF" , fill = "dodgerblue3") + 
    geom_text(aes(label=Value), position=position_dodge(width=0.9), hjust= -.25,vjust=0.25 ,size =3.5 , angle = 90) 

回答

3

通行證上y軸的geom_text位置y = Value + 2 * sign(Value)

library(ggplot2) 
ggplot(dat, aes(Types, Value)) + 
    geom_bar(stat = "identity" ,color = "#FFFFFF" , fill = "dodgerblue3") + 
    geom_text(aes(y = Value + 2 * sign(Value), label = Value), 
       position = position_dodge(width = 0.9), 
       size = 3.5 , angle = 90) 

enter image description here

有輕微的視覺調整,我在我的情節做另一個情節:
正如你有酒吧的數字,你不需要Y軸(它的多餘的)。

ggplot(dat, aes(Types, Value)) + 
    geom_bar(stat = "identity", color = "black" , fill = "grey", 
      size = 0.7, width = 0.9) + 
    geom_text(aes(y = Value + 2 * sign(Value), label = Value), 
       position = position_dodge(width = 0.9), 
       size = 5) + 
    theme_classic() + 
    theme(axis.text.x = element_text(size = 12), 
      axis.title = element_text(size = 20), 
      axis.text.y = element_blank(), 
      axis.line = element_blank(), 
      axis.ticks = element_blank()) 

enter image description here