Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(ggplot2)
- library(dplyr)
- library(grid)
- library(gridExtra)
- numSamples <- 200L
- DF <- data.frame(V1 = sample(1L:4L, numSamples, TRUE),
- V2 = sample(1L:2L, numSamples, TRUE))
- sum0 <- DF %>% group_by(V1) %>% summarise (mean = mean(V2), n = n())
- ggplotColours <- function(n = 6, h = c(0, 360) + 15){
- if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
- hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
- }
- transDblAxisForBar <- function(x, y) {
- return((y - min(y)) / (max(y) - min(y)) * extendrange(x)[2])
- }
- cols <- ggplotColours(2)
- sum0 %>% ggplot(aes(x = V1, y = n)) +
- geom_bar(position = "stack", stat = "identity", fill = cols[1]) +
- geom_line(aes(x = V1, y = transDblAxisForBar(n, mean)), col = cols[2], lwd = 1.5) +
- geom_text(aes(label= n), vjust = 1.5, colour = "black",
- position = position_dodge(0.9), size = 5) +
- geom_text(aes(x = V1, y = transDblAxisForBar(n, mean), label= sprintf("%.2f", mean)),
- vjust = -1.5, colour = "black", position = position_dodge(0.9), size = 5) +
- ylim(c(0, max(sum0$n) * 1.1)) +
- theme(axis.title.y = element_blank(), axis.text.y = element_blank(),
- axis.ticks.y = element_blank())
Advertisement
Add Comment
Please, Sign In to add comment