根据值绘制一个变量,仅线和点

F. *_*zil 6 r ggplot2

我想使用 ggplot2 在同一个图中绘制 3 个时间序列。我想将前 2 个系列绘制为没有点的实线。我想用点而不是线来绘制第三个系列。我怎样才能做到这一点?

library(ggplot2)
library(reshape2)

d1 <- c(1, 2, 3, 2, 1, 2, 3, 4, 5, 6, 5, 4, 3, 1)
d2 <- c(0, 2, 4, 5, 4, 3, 2, 4, 6, 7, 6, 5, 3, 1)
d3 <- c(0, 1, 2, 4, 4, 2, 1, 3, 4, 7, 8, 3, 5, 0)

ts1 <- ts(d1, c(2015, 01), c(2016, 03), frequency = 12)
ts2 <- ts(d2, c(2015, 01), c(2016, 03), frequency = 12)
ts3 <- ts(d3, c(2015, 01), c(2016, 03), frequency = 12)

# prepare data for ggplot
dat <- ts.union(ts1, ts2, ts3)
dat <- melt(dat, id.vars = "x")

# add dates
dates <- seq(as.Date("2015-01-01"), as.Date("2016-03-01"), by = "months")
dat$Date <- dates

p <- ggplot(dat, aes(x = Date, y = value, col = Var2)) +
  geom_line(aes(linetype = Var2), size = 1) +
  geom_point(aes(shape = Var2), size = 2) +
  scale_linetype_manual(values = c(1, 1, 1)) +
  scale_shape_manual(values = c(0, 1, 2))
print(p)
Run Code Online (Sandbox Code Playgroud)

Tun*_*ung 4

要进一步采用 @Rui Barradas 的解决方案,您可以通过guide_legend/override.aes()给出线形状和点线型来修改线和NA点的图例NA

my_color <- setNames(c("red", "blue", "green"),
                     c('ts1', 'ts2', 'ts3'))
ggplot(dat, aes(x = Date, y = value, colour = Var2)) +
  geom_line(data = subset(dat, Var2 != "ts3")) +
  geom_point(data = subset(dat, Var2 == "ts3")) +
  scale_color_manual("Legend", values = my_color) +
  guides(color = guide_legend(override.aes = list(linetype = c(1,   1, NA),
                                                  shape    = c(NA, NA, 19)))) +
  theme_classic(base_size = 14)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2019-12-22 创建

  • 这是非常好的。我仍然无法摆脱这个问题一定是个骗子的感觉...... (2认同)