绘制数据并使用图例插入样条曲线

时间:2016-10-05 16:29:14

标签: r ggplot2 spline

示例数据:

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 ))

对于每个方面,我想使用蓝点为数据绘制数据,并使用红色连续线绘制样条插值。此外,我想得到一个很好的传奇,条目“数据”和“样条”:显然,所有方面的传说都是相同的。我能够绘制点和线:

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")

enter image description here

如何添加图例?

2 个答案:

答案 0 :(得分:1)

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中我定义颜色(蓝色和番茄)

答案 1 :(得分:0)

这样的事情对你有用:

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)

enter image description here