使用图例绘制数据和插值样条

plot data and interpolating spline with a legend

示例数据:

x <- seq(0, 1, by = 0.1)
y <- c(1, 2.1, 3, 2, 1, 0, -3, -2, 0, 0.5, 1)
xpred <- seq(0, 1, by = 0.01)
ypred <- spline(x, y, xout = xpred)$y
y1 <- y + runif(length(y))
ypred1 <- spline(x, y1, xout = xpred)$y
nx <- length(x)
nxpred <- length(xpred)
foo <- data.frame(x = c(x, xpred, x, xpred), y =c(y, ypred, y1, ypred1),
       type = rep(c(rep("data", times = nx), rep("spline", times = nxpred))), 
       experiment = rep(c("A", "B"), each = nx + nxpred ))

对于每个方面,我想使用蓝色点作为数据绘制数据,使用红色连续线作为样条插值。另外,我想得到一个漂亮的图例,其中包含条目 "Data" 和 "Spline":显然,图例对于所有方面都是相同的。我能够绘制点和线:

library(dplyr)
library(ggplot2)
ggplot(data = filter(foo, type =="spline"), aes(x=x, y=y)) +
geom_line(color = "tomato") +
geom_point(data = filter(foo, type =="data"), color ="blue") +
facet_wrap(~ experiment, labeller = "label_both")

如何添加图例?

ggplot(data = filter(foo, type =="spline"), aes(x=x, y=y)) +
  geom_line(aes(color = "Spline")) +
  geom_point(data = filter(foo, type =="data"), aes(color ="Data")) +
  facet_wrap(~ experiment, labeller = "label_both")+
  scale_colour_manual(name="Legend",values=c("blue","tomato"))

如果您想要图例,您需要在 aes() 中添加颜色。
在 aes 中,我设置了将出现在图例中的名称(根据您的需要进行编辑)。
在 scale_colour_manual 中,我定义了颜色(蓝色和番茄)

像这样的东西应该适合你:

ggplot(data=foo) + 
geom_point(data=foo[foo$type=='data',], aes(x, y), col='red') + 
geom_line(data=foo[foo$type=='spline',], aes(x, y), col='blue') + 
facet_wrap(~experiment)