rnso
rnso

Reputation: 24535

Drawing bar between 2 variable values in R

I have following data:

> mydf
  name var1 var2
1   aa  120   80
2   bb  128   86
3   cc  132   98

> dput(mydf)
structure(list(name = structure(1:3, .Label = c("aa", "bb", "cc"
), class = "factor"), var1 = c(120L, 128L, 132L), var2 = c(80L, 
86L, 98L)), .Names = c("name", "var1", "var2"), class = "data.frame", row.names = c(NA, 
-3L))

I want to create a graph similar to following (which is manually drawn and not accurate to scale):

enter image description here

How can this be done (preferably with ggplot)? Thanks for your help.

Upvotes: 1

Views: 98

Answers (1)

MrFlick
MrFlick

Reputation: 206197

Here's a start at least

ggplot(transform(mydf, xname=as.numeric(name))) + 
    geom_rect(aes(xmin=xname-.2, xmax=xname+.2, ymin=var1, ymax=var2)) + 
    geom_text(aes(x=xname, y=var1+5, label=var1)) + 
    geom_text(aes(x=xname, y=var2-5, label=var2)) + 
    scale_x_continuous(breaks=1:nlevels(mydf$name), labels=levels(mydf$name)) + 
    ylab("units") + xlab("")

which produces

enter image description here

Upvotes: 1

Related Questions