Custom ggplot2 shaded error areas on categorical line plot

試著忘記壹切 提交于 2019-12-04 19:31:16

Here's one way to add smoothed versions of upper and lower. We'll add LOESS predictions for upper and lower to the data frame and then plot those using geom_ribbon. It would be more elegant if this could all be done within the call to ggplot. That's probably possible by feeding a special-purpose function to stat_summary, and hopefully someone else will post an answer using that approach.

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

And here's the result:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!