celestialgod

ggplot2: double axis with labels

Jun 13th, 2017
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.19 KB | None | 0 0
  1. library(ggplot2)
  2. library(dplyr)
  3. library(grid)
  4. library(gridExtra)
  5.  
  6. numSamples <- 200L
  7. DF <- data.frame(V1 = sample(1L:4L, numSamples, TRUE),
  8.                  V2 = sample(1L:2L, numSamples, TRUE))
  9. sum0 <- DF %>% group_by(V1) %>% summarise (mean = mean(V2), n = n())
  10.  
  11. ggplotColours <- function(n = 6, h = c(0, 360) + 15){
  12.   if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
  13.   hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
  14. }
  15.  
  16. transDblAxisForBar <- function(x, y) {
  17.   return((y - min(y)) / (max(y) - min(y)) * extendrange(x)[2])
  18. }
  19.  
  20. cols <- ggplotColours(2)
  21. sum0 %>% ggplot(aes(x = V1, y = n)) +
  22.   geom_bar(position = "stack", stat = "identity", fill = cols[1]) +
  23.   geom_line(aes(x = V1, y = transDblAxisForBar(n, mean)), col = cols[2], lwd = 1.5) +
  24.   geom_text(aes(label= n), vjust = 1.5, colour = "black",
  25.             position = position_dodge(0.9), size = 5) +
  26.   geom_text(aes(x = V1, y = transDblAxisForBar(n, mean), label= sprintf("%.2f", mean)),
  27.             vjust = -1.5, colour = "black", position = position_dodge(0.9), size = 5) +
  28.   ylim(c(0, max(sum0$n) * 1.1)) +
  29.   theme(axis.title.y = element_blank(), axis.text.y = element_blank(),
  30.         axis.ticks.y = element_blank())
Advertisement
Add Comment
Please, Sign In to add comment