-2

I have a table:

> DT
id      start        end place
1: id1 2014-01-01 2014-02-01 town1
2: id1 2014-02-01 2014-04-01 town2
3: id2 2014-01-01 2014-02-01 town2
4: id2 2014-03-01 2014-05-01 town4
5: id3 2014-01-01 2015-02-01 town3

I need to plot a chart with X=timeline, Y=id and each row should be displayed as a series of bars (length depends on start and end dates, and color depends on place).

Graph example: (without timeline labels): enter image description here

For example, I'm trying

ggplot(DT,aes(start,id,colour=place))+geom_bar()

Of course it doesn't work

stat_count() must not be used with a y aesthetic.

And I need to include end date in chart.

raw data:

id1;2014-01-01;2014-02-01;town1
id1;2014-02-01;2014-04-01;town2
id2;2014-01-01;2014-02-01;town2
id2;2014-03-01;2014-05-01;town4
id3;2014-01-01;2015-02-01;town3
Sergey N Lukin
  • 575
  • 2
  • 16

2 Answers2

1

To get it working, just change geom_bar slightly:

ggplot(DT,aes(start,id, fill=place))+geom_bar(stat="identity")

That being said, you might want to consider something else for a timeline. Try this blog post on r-bloggers.

enter image description here

CAFEBABE
  • 3,983
  • 1
  • 19
  • 38
Oliver Frost
  • 827
  • 5
  • 18
1

You mean something along

start <- c("2014-01-01","2014-02-01","2014-01-01","2014-01-01","2014-02-01")
end <-  c("2014-02-01","2014-04-01","2014-02-01","2014-05-01","2014-03-01")
id <- c("id1","id1","id2","id2","id3")
evnt <- c("town1","town2","town2","town4","town3")
df<-data.frame(start,end,id,evnt)
p <- ggplot(df, aes(xmin=as.Date(start),xmax=as.Date(end),
                    ymin=as.numeric(id)-0.5,ymax=as.numeric(id)+0.5,
                    fill=evnt))+geom_rect()
p <- p+ylim(levels(df$id))

p

You're example wasn't containig the data frame in reproducible form. Hence, you might need to adapt (c.f. https://stackoverflow.com/help/mcve)

enter image description here

Community
  • 1
  • 1
CAFEBABE
  • 3,983
  • 1
  • 19
  • 38
  • id is not conitunues and numeric, If I changes to "factor", geom_rect doesn't work well. ggplot(df, aes(xmin=as.Date(start),xmax=as.Date(end), + ymin=factor(id),ymax=factor(id)+1, + fill=evnt))+geom_rect() because "+" not defined on factor. – Sergey N Lukin Feb 17 '16 at 08:46
  • wasn't a continuum in my code either. I guess your problem is mainly on the labels. Fixed that one. – CAFEBABE Feb 17 '16 at 19:06
  • @SergeyNLukin Is there still something missing? It using the id of a factor to map the y axis. Hence it is discrete on this axis. I'm curious what you want to achieve if this is not the answer. – CAFEBABE Feb 18 '16 at 07:55
  • It was my problem, i use data.table and first column has different class: class(df$id) - factor, class(dt$id) - character. – Sergey N Lukin Feb 19 '16 at 07:50