Christian Leach
Christian Leach

Reputation: 21

Creating a legend for a gantt chart with ggplot2

Ok so I'm trying to do something simple but can't seem to get it done. I want to make a legend for the points on the graph, however, no matter what I do I cant seem to make it work. If you could help me make a legend for both the points and the lines created in the ggplot, I would really appreciate it! the shape 15 points should be "Enter market" and the shape 19 should be "Exit market".

table1 <- as.data.frame(matrix(c(
"Drug1",      "Filing", "2020-04-12",
"Drug2",      "Filing", "2020-05-12",
"Drug3",      "Filing", "2020-04-23",
"Drug4",      "Filing", "2020-01-27",
"Drug5",      "Filing", "2020-02-02",
"Drug1",      "Approval", "2021-04-12",
"Drug2",      "Approval", "2021-06-12",
"Drug3",      "Approval", "2021-07-23",
"Drug4",      "Approval", "2021-04-27",
"Drug5",      "Approval", "2021-03-02"),byrow = TRUE,ncol=3,nrow=10))
colnames(table1) <- c("Name", "variable", "value")
table1$value <- as.Date(table1$value)

ggplot(table1 , aes(as.Date(value, "%m/%d/%Y"), Name))+ 
  geom_point(data= table1 [table1 $variable=="Filing",], aes(as.Date(value, "%m/%d/%Y"), Name), shape=15, size = 3.5)+
  geom_point(data= table1 [table1 $variable=="Approval",], aes(as.Date(value, "%m/%d/%Y"), Name), shape=19, size = 3.5)+
  geom_line(data=(table1 [table1 $variable=="Filing" |  table1 $variable=="Approval",]), aes(as.Date(value, "%m/%d/%Y"), Name), linetype="solid", size=1)

Upvotes: 1

Views: 179

Answers (1)

Christian Leach
Christian Leach

Reputation: 21

I figured it out on my own here you go!

table1 <- as.data.frame(matrix(c(
"Drug1",      "Filing", "2020-04-12",
"Drug2",      "Filing", "2020-05-12",
"Drug3",      "Filing", "2020-04-23",
"Drug4",      "Filing", "2020-01-27",
"Drug5",      "Filing", "2020-02-02",
"Drug1",      "Approval", "2021-04-12",
"Drug2",      "Approval", "2021-06-12",
"Drug3",      "Approval", "2021-07-23",
"Drug4",      "Approval", "2021-04-27",
"Drug5",      "Approval", "2021-03-02"),byrow = TRUE,ncol=3,nrow=10))
colnames(table1) <- c("Name", "variable", "value")
table1$value <-as.Date(table1$value)

shapes  <- c("s1" = 15, "s2" = 19)

ggplot(table1 , aes(as.Date(value, "%m/%d/%Y"), Name))+ 
  geom_point(data= table1 [table1 $variable=="Filing",], aes(as.Date(value, "%m/%d/%Y"), Name,   shape = "s1"),size=3)+
  geom_point(data= table1 [table1 $variable=="Approval",], aes(as.Date(value, "%m/%d/%Y"), Name,   shape = "s2"),size=3)+
  geom_line(data=(table1 [table1 $variable=="Filing" |  table1 $variable=="Approval",]), aes(as.Date(value, "%m/%d/%Y"), Name), linetype="solid", size=1)+
  scale_shape_manual(breaks = c("s1", "s2"),values=c("s1" = 15, "s2" = 19),labels = c("Filing Date", "Approval Date"))

Upvotes: 1

Related Questions