0

I have a dataframe like:

enter image description here

I would like to obtain a barplot with, for each bin, two bars (up and down) and the text of upIDX above the up's bars and text of downIDX above the down's bars like

enter image description here

On ggplot2, I could generate the graph with the two bars for each bin but I wasn't able to add the labels above the bars. Here is the script I wrote:

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()

Can someone could help me?

1
  • Use dput(df3) and add the result to your post instead of showing a screenshot of your data. (The first one can easily be copied and pasted into an R session to reproduce the data set) Commented Jan 17, 2017 at 16:51

2 Answers 2

2

You can do something like this:

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can also use 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

1 Comment

how is this any different than the post below? (besides qplot)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.