设置geom_vline的线型?

Ign*_*cio 6 r ggplot2

对于以下情节:

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 ~ .)
Run Code Online (Sandbox Code Playgroud)

我想让"AB"的线型为"dotdash",而"AA"为"longdash".我该如何指定?

Ben*_*ker 11

使用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 ~ .)
Run Code Online (Sandbox Code Playgroud)

来自?par:

'lty'线型.线型可以指定为整数(0 =空白,1 =实线(默认),2 =虚线,3 =点,4 = dotdash,5 = longdash,6 = twodash)或作为其中一个字符串'"空白"','"solid"','"虚线"','"点缀"','"dotdash"','"longdash"'或'"twodash"',其中'"blank"'使用'隐形行'(即,不绘制它们).

所以

g0 + scale_linetype_manual(values=c(5,4))
Run Code Online (Sandbox Code Playgroud)

或者(可能更好!)

g0 + scale_linetype_manual(values=c("longdash","dotdash"))
Run Code Online (Sandbox Code Playgroud)

  • 虽然这没有任何问题,但您也可以添加linetype作为参数.(例如geom_vline(xintercept = 0,color ="gray",linetype ="dashed",size = 0.5)).如果您已经使用scale_linetype_manual指定由geom_line()添加的行,则这可能更方便. (2认同)