celestialgod

ggplot2: double axis 2

Jun 14th, 2017
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.01 KB | None | 0 0
  1. library(ggplot2)
  2. library(dplyr)
  3.  
  4. numSamples <- 200L
  5. DF <- data.frame(V1 = sample(1L:4L, numSamples, TRUE),
  6.                  V2 = sample(1L:2L, numSamples, TRUE))
  7. sum0 <- DF %>% group_by(V1) %>% summarise (mean = mean(V2), n = n())
  8.  
  9. ggplotColours <- function(n = 6, h = c(0, 360) + 15){
  10.   if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
  11.   hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
  12. }
  13.  
  14. transDblAxisForBar <- function(x, y) {
  15.   return((y - min(y)) / (max(y) - min(y)) * extendrange(x)[2])
  16. }
  17.  
  18. cols <- ggplotColours(2)
  19. ggplot(sum0, aes(V1, n)) +
  20.   geom_bar(position = "stack", stat = "identity", fill = cols[1]) +
  21.   geom_line(aes(x = V1, y = transDblAxisForBar(n, mean)),
  22.             col = cols[2], lwd = 1.5) +
  23.   scale_y_continuous("n", sec.axis = sec_axis(~ . / extendrange(sum0$n)[2] *  
  24.                                                    diff(range(sum0$mean)) +
  25.                                                    min(sum0$mean),
  26.                                                  name = "mean"))
Advertisement
Add Comment
Please, Sign In to add comment