Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

r - Put labels over negative and positive geom_bar

I'd like to visualize a data using bar chart and ggplot.

I have the data below, when I want to vis this data the text for negative values are not showing below the 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)

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pass position of geom_text on y axis with 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

Another plot with minor visual tweaks that I do on my plots:
As you have numbers with bars you don't need y-axis (it's redundant).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...