我有一个类似的数据框:
我想获得一个条形图,对于每个bin,两个条形图(向上和向下)和upIDX的文本高于向下条形图上方的条形图和文本downIDX
,如
在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()
有人可以帮助我吗?
答案 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)
答案 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)