1

I have a dataset with odds ratios and Confidence interval of each odds ratio, plotted with errorbars. I have included a shaded area to indicate the variation of confidence intervals as follows

Link to ggplot graph

set.seed(10)
y <- runif(18, 0, 5)                  # Odds ratios
spread <- runif(18, 0, 2)             # Confidence intervals
CI_hi <- y + spread/2                 # The upper level of CIs
CI_lo <- y - spread/2                 # Lower level of CIs
x <- seq(from=0.3, to=2.0, by=0.1)    # x-values

library(ggplot2)
ggplot(data = NULL, aes(x=x, y=y)) +
  geom_point(shape=18, color="deepskyblue3") +
  geom_errorbar(aes(ymin=CI_lo, ymax=CI_hi), width=.0, color="deepskyblue3") +
  geom_hline(yintercept = 1, color="darkgrey") +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1),
    panel.background = element_blank(),
    axis.ticks.y = element_blank(),
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_line(size = 0.25, linetype = 'solid', colour = "grey"),
    panel.grid.minor.x = element_blank(),
    panel.grid.minor.y = element_blank(),
    text=element_text(family="Georgia", size=12)
    ) +
  geom_polygon(aes(x=append(x,rev(x)), y=append(CI_hi,rev(CI_lo))), alpha=0.2) +
  ylab("Odds ratio") +
  xlab("Some variable")

Is there a way to smoothen the edges of the shaded area?

tjebo
  • 21,977
  • 7
  • 58
  • 94
pha
  • 316
  • 2
  • 9

1 Answers1

4

You can create splines and use them with geom_ribbon. Or just leave the shading and use ggalt::geom_xspline

library(tidyverse)

set.seed(10)
y <- runif(18, 0, 5)                  # Odds ratios
spread <- runif(18, 0, 2)             # Confidence intervals
CI_hi <- y + spread/2                 # The upper level of CIs
CI_lo <- y - spread/2                 # Lower level of CIs
x <- seq(from=0.3, to=2.0, by=0.1)    # x-values

foo <- data.frame(x,y, CI_hi, CI_lo)

foolong <- foo %>% 
  pivot_longer(names_to = 'CI', values_to = 'val', contains("CI"))
# use ggalt::geom_xspline

ggplot(data = NULL, aes(x=x, y=y)) +
  geom_errorbar(aes(ymin=CI_lo, ymax=CI_hi), width=.0, color="deepskyblue3") +
  geom_polygon(aes(x=append(x,rev(x)), y=append(CI_hi,rev(CI_lo))), alpha=0.2) +
  ggalt::geom_xspline(data = foolong, aes(x = x, y = val, group = CI))

# make your own splines

spline_x <- spline(foo$x, foo$CI_hi)[["x"]]
spline_hi<- spline(foo$x, foo$CI_hi)[["y"]]
spline_lo<- spline(foo$x, foo$CI_lo)[["y"]]

foo_ribbon <- data.frame(spline_x, spline_hi, spline_lo)

ggplot(data = NULL, aes(x=x, y=y)) +
  geom_errorbar(aes(ymin=CI_lo, ymax=CI_hi), width=.0, color="deepskyblue3") +
  geom_ribbon(data = foo_ribbon, 
              aes(x = spline_x, y = NULL, ymin = spline_lo, ymax = spline_hi), 
              alpha= 0.2, color = 'grey')

Created on 2020-04-22 by the reprex package (v0.3.0)

Helpful thread: plotting smooth line through all data points

tjebo
  • 21,977
  • 7
  • 58
  • 94