ShanZhengYang
ShanZhengYang

Reputation: 17631

Using ggplot2 to generate a barplot based on intervals of values

I have the following R data.table:

library(data.table)

dt1 = data.table(start = c(0, 3, 5, 7), end  = c(3, 5, 7, 10), size = c(0, 3, 2, 1))

print(dt1)
   start end size
1:     0   3    0
2:     3   5    3
3:     5   7    2
4:     7  10    1

I wanted to plot a barplot with ggplot2, whereby each interval is plotted by size. Is there a clear way forward how to accomplish this with ggplot2?

foo = data.table(x = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 
          size = c(0, 0, 0, 3, 3, 3, 2, 2, 1, 1, 1))

ggplot(data=foo, aes(x=x, y=size)) + geom_bar(stat="identity")

enter image description here

That's roughly what I have in mind, but not right. The interval from 3 to 5 should be one solid line, not three lines.

Is this a standard procedure with ggplot2?

Upvotes: 0

Views: 414

Answers (1)

Wil
Wil

Reputation: 3178

You could use geom_rect() as follows

ggplot(dt1,aes(xmin = start,xmax = end, ymin = 0,ymax = size)) + 
  geom_rect()

enter image description here

Upvotes: 3

Related Questions