Adding a manual right-hand-side y-axis in ggplot2

Viewed 183

I am wondering if there is any way to get a manual right-side y-axis label when there is no scale, only facet headings.

Here's an example

library(dplyr)
library(Hmisc)

# Plot power vs. n for various odds ratios  (base prob.=.1)
(n  <- seq(10, 1000, by=10)) # candidate sample sizes

(OR <- as.numeric(sort(c(seq(1/0.90,1/0.13,length.out = 9),2.9)))) # candidate odds ratios, spanning the 95% CI centered around an odds ratio of 2.9

alpha <- c(.001, .01, .05)

# put all of these into a dataset and calculate power
powerDF <- data.frame(expand.grid(OR, n, alpha)) %>% 
           rename(OR = Var1, num = Var2, alph = Var3) %>%
           arrange(OR) %>%
           mutate(power = as.numeric(bpower(p1=.29, odds.ratio=OR, n=num, alpha = alph))) %>%
           transform(OR = factor(format(round(OR,2),nsmall=2)))

# now plot
pPower <- ggplot(powerDF, aes(x = num, y = power, colour = factor(OR))) + 
                 geom_line() +
                 facet_grid(factor(alph)~.) +
                 labs(x = "sample size") +
                 scale_colour_discrete(name = "Odds Ratio") +
                 scale_x_continuous(breaks = seq(0,1000,100)) +
                 scale_y_continuous(breaks = seq(0,1,.1)) +
                 theme_light() +
                 theme(axis.title.x = element_text(size = 12, face = "bold"),
                       axis.title.y = element_text(size = 12, face = "bold"),
                       axis.text = element_text(size = 11),
                       panel.grid.minor = element_blank(),
                       panel.grid.major.y = element_line(colour = "gray95"),
                       panel.grid.major.x = element_line(colour = "gray95"),
                       strip.text = element_text(colour = 'black', face = 'bold', size = 12),
                       legend.text = element_text(size = 12),
                       legend.title = element_text(size = 12, face = "bold"))

enter image description here

(Please forgive the cluttered axes labels, I had to reduce the size of the image to allow it to be uploaded).

I was wondering if there was any way to have an axis label saying 'significance level' down the right hand side of the graph?

1 Answers

Adding the following to scale_y_continuous seems one way to go (although a bunch of warnings)

sec.axis = sec_axis(trans=I, breaks=NULL, name="Significance")

Alternatively, you can add an additional strip that spans all the panels:

library(grid)
library(gtable)

g <- ggplotGrob(pPower)
rect <- grobTree(rectGrob(gp = gpar(fill = "grey70", col="grey70")),
              textGrob("Significance",  rot=-90, gp = gpar(col="black")))
g <- gtable_add_cols(g, g$widths[6], 6)
g <- gtable_add_grob(g, rect, l=7, t=7, b=11)
grid.newpage() ; grid.draw(g)
Related