1

我正在尝试绘制一条由黄土平滑的线,但我试图弄清楚如何包含由现有变量定义的阴影错误区域,但也要平滑。

此代码创建示例数据:

set.seed(12345)
data <- cbind(rep("A", 100), rnorm(100, 0, 1))
data <- rbind(data, cbind(rep("B", 100), rnorm(100, 5, 1)))
data <- rbind(data, cbind(rep("C", 100), rnorm(100, 10, 1)))
data <- rbind(data, cbind(rep("D", 100), rnorm(100, 15, 1)))
data <- cbind(rep(1:100, 4), data)
data <- data.frame(data)
names(data) <- c("num", "category", "value")
data$num <- as.numeric(data$num)
data$value <- as.numeric(data$value)
data$upper <- data$value+0.20
data$lower <- data$value-0.30

绘制下面的数据,这就是我得到的:

ggplot(data, aes(x=num, y=value, colour=category)) +
  stat_smooth(method="loess", se=F)

在此处输入图像描述

我想要的是一个如下所示的图,除了阴影区域的上限和下限由生成数据中的“上”和“下”变量的平滑线界定。

在此处输入图像描述

任何帮助将不胜感激。

4

1 回答 1

3

upper这是添加和的平滑版本的一种方法lower。我们将为数据框添加 LOESS 预测,upper然后lower使用geom_ribbon. 如果这一切都可以在对ggplot. 这可能通过向 提供一个特殊用途的函数来实现stat_summary,并希望其他人会使用这种方法发布答案。

# Expand the scale of the upper and lower values so that the difference
# is visible in the plot
data$upper = data$value + 10
data$lower = data$value - 10

# Order data by category and num
data = data[order(data$category, data$num),]

# Create LOESS predictions for the values of upper and lower 
# and add them to the data frame. I'm sure there's a better way to do this,
# but my attempts with dplyr and tapply both failed, so I've resorted to the clunky 
# method below.
data$upperLoess = unlist(lapply(LETTERS[1:4], 
                  function(x) predict(loess(data$upper[data$category==x] ~ 
                                                  data$num[data$category==x]))))
data$lowerLoess = unlist(lapply(LETTERS[1:4], 
                  function(x) predict(loess(data$lower[data$category==x] ~ 
                                                  data$num[data$category==x]))))

# Use geom_ribbon to add a prediction band bounded by the LOESS predictions for 
# upper and lower
ggplot(data, aes(num, value, colour=category, fill=category)) +
  geom_smooth(method="loess", se=FALSE) +
  geom_ribbon(aes(x=num, y=value, ymax=upperLoess, ymin=lowerLoess), 
              alpha=0.2)

结果如下:

在此处输入图像描述

于 2014-10-16T06:18:00.977 回答