ggplot2在多个条形图上添加文本

时间:2017-01-17 16:15:26

标签: r ggplot2

我有一个类似的数据框:

enter image description here

我想获得一个条形图,对于每个bin,两个条形图(向上和向下)和upIDX的文本高于向下条形图上方的条形图和文本downIDX,如

enter image description here

ggplot2上,我可以为每个bin生成两个条形图,但我无法在条形图上方添加标签。这是我写的脚本:

df3<-melt(df3,id='bin')
ggplot(df3,aes(x=factor(df3$bin,levels=df3$bin),y=df3$value,fill=df3$variable))+
  geom_bar(stat='identity',position = 'dodge')+
  coord_flip()

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

您可以这样做:

library(data.table)
library(ggplot2)
df<- data.table(bin=LETTERS[1:4], up=c(9,8,13,2),down=c(0,5,2,1),upIDX=0,downIDX="n")
df <- melt(df, id=1, measure=list(2:3, 4:5))
df[,variable:=factor(variable, labels=c("up", "down"))]
ggplot(df, aes(bin,value1,fill=variable)) + 
  geom_col(position="dodge") + 
  geom_text(aes(label=value2), position=position_dodge(.9), vjust=0)

enter image description here

答案 1 :(得分:0)

您也可以使用qplot():

library(data.table)
library(ggplot2)
df<- data.table(bin=LETTERS[1:4], up=c(9,8,13,2),down=c(0,5,2,1),upIDX=0,downIDX="n")
df <- melt(df, id=1, measure=list(2:3, 4:5))
df[,variable:=factor(variable, labels=c("up", "down"))]

qplot(bin,value1,data = df,fill = df$variable)+geom_col(position="dodge") +  geom_text(aes(label=value2),position=position_dodge(.9), vjust=-0.4)

The chart