Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set linetype for geom_vline?

Tags:

r

ggplot2

For the following plot:

df.plot <-structure(list(color = structure(c(2L, 2L, 3L, 1L, 3L, 4L, 3L, 
    1L, 4L, 1L, 2L, 4L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 
    3L, 3L, 3L, 3L), .Label = c("54", "55", "61", "69"), class = "factor"), 
    date = structure(c(16687, 16687, 16687, 16687, 16687, 16687, 
    16688, 16688, 16688, 16689, 16689, 16690, 16693, 16693, 16693, 
    16694, 16694, 16695, 16695, 16695, 16695, 16696, 16696, 16696, 
    16696, 16696, 16696), class = "Date"), facet = c("A", 
     "A", "A", "A", "A", "B", 
     "B", "A", "B", "B", "B", "B", 
     "B", "B", "B", "B", "A", "B", 
     "A", "B", "A", "C", "B", "C", 
     "C", "B", "C")), class = "data.frame", row.names = c(NA, -27L), 
     .Names = c("color", "date", "facet"))

vlines <- data.frame(date = as.Date(c("2015-09-10", "2015-09-13")), 
          LType=(c("AA", "AB")))
ggplot(df.plot, aes(x=date, fill=color)) + 
  geom_dotplot(binwidth=1, stackgroups=TRUE, binpositions="all") +
  coord_fixed(ratio=1) + 
  ylim(0,7) +
  geom_vline(data=vlines, aes(xintercept = as.numeric(date), linetype=LType))  + 
  facet_grid(facet ~ .)

I would like to make the line type for "AB" be "dotdash" , and for "AA" "longdash". How can I specify that?

like image 302
Ignacio Avatar asked Mar 23 '16 13:03

Ignacio


1 Answers

Use scale_linetype_manual.

library("ggplot2")
g0 <- ggplot(df.plot, aes(x=date, fill=color)) + 
  geom_dotplot(binwidth=1, stackgroups=TRUE, binpositions="all") +
  coord_fixed(ratio=1) + 
  ylim(0,7) +
  geom_vline(data=vlines, aes(xintercept = as.numeric(date), linetype=LType))  + 
  facet_grid(facet ~ .)

From ?par:

‘lty’ The line type. Line types can either be specified as an integer (0=blank, 1=solid (default), 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash) or as one of the character strings ‘"blank"’, ‘"solid"’, ‘"dashed"’, ‘"dotted"’, ‘"dotdash"’, ‘"longdash"’, or ‘"twodash"’, where ‘"blank"’ uses ‘invisible lines’ (i.e., does not draw them).

So

g0 + scale_linetype_manual(values=c(5,4))

or (probably better!)

g0 + scale_linetype_manual(values=c("longdash","dotdash"))

If you are drawing a single vline, or if you are already using scale_linetype_manual() to specify line types for a geom_line(), it's easier/makes more sense to use linetype as an argument:

geom_vline(xintercept = <something>, linetype="dotdash")
like image 192
Ben Bolker Avatar answered Oct 15 '22 05:10

Ben Bolker