|
| 1 | +#' Make a pie chart using ggplot2 |
| 2 | +#' |
| 3 | +#' @description |
| 4 | +#' The function \code{pie_maker} creates a pie chart using |
| 5 | +#' \code{ggplot2}. It takes two vectors of values and optionally a |
| 6 | +#' second vector of values to create a pie chart with two layers. |
| 7 | +#' @param x1 A numeric vector containing the values for the first |
| 8 | +#' layer of the pie chart. |
| 9 | +#' @param cols A character vector containing the colors for the |
| 10 | +#' slices of the pie chart. |
| 11 | +#' @param x2 An optional numeric vector containing the values for the |
| 12 | +#' second layer of the pie chart. |
| 13 | +#' @param label An optional character string to be used as the title |
| 14 | +#' @param ... Currently not used. |
| 15 | +#' @examples |
| 16 | +#' pieplot(x1 = c(143, 459), |
| 17 | +#' cols = c("#44aa99", "#117733")) |
| 18 | +#' |
| 19 | +#' pieplot(x1 = c(61 - 9, 9, 593, 3595 - 593), |
| 20 | +#' cols = c("#bbbbbb", "#44aa99", "#117733", "#dddddd"), |
| 21 | +#' x2 = c(61, 3595)) |
| 22 | +#' |
| 23 | +#' @return ggplot object |
| 24 | +#' @import ggplot2 |
| 25 | +#' |
| 26 | +#' @export |
| 27 | + |
| 28 | + |
| 29 | +pieplot <- function(x1, cols, x2 = NULL, label = NULL, ...) { |
| 30 | + pcolours <- ymin <- ymax <- NULL |
| 31 | + df <- data.frame( |
| 32 | + pvalues = x1, |
| 33 | + pcolours = as.factor(seq_along(cols)) |
| 34 | + ) |
| 35 | + cs <- cumsum(x1) |
| 36 | + df$ymin <- c(0, cs[seq_along(cs) - 1]) |
| 37 | + df$ymax <- cs |
| 38 | + if (is.null(x2)) { |
| 39 | + df2 <- df |
| 40 | + } else { |
| 41 | + cs <- cumsum(x2) |
| 42 | + df2 <- data.frame( |
| 43 | + pvalues = x2, |
| 44 | + ymin = c(0, cs[seq_along(cs) - 1]), |
| 45 | + ymax = cs |
| 46 | + ) |
| 47 | + } |
| 48 | + |
| 49 | + p <- ggplot() + |
| 50 | + geom_rect(data = df, aes(fill = pcolours, |
| 51 | + ymin = ymin, ymax = ymax, xmin = 0, xmax = 3)) + |
| 52 | + scale_fill_manual(values = cols) + |
| 53 | + geom_rect(data = df2, aes(ymin = ymin, ymax = ymax, |
| 54 | + xmin = 0, xmax = 3), |
| 55 | + alpha = 0, colour = "black") + |
| 56 | + xlim(c(0, 3)) + |
| 57 | + theme_minimal() + |
| 58 | + theme(aspect.ratio = 1) + |
| 59 | + coord_polar(theta = "y") + |
| 60 | + theme( |
| 61 | + axis.text = element_blank(), |
| 62 | + axis.ticks = element_blank(), |
| 63 | + axis.title = element_blank(), |
| 64 | + panel.grid = element_blank(), |
| 65 | + legend.position = "none" |
| 66 | + ) |
| 67 | + if (!is.null(label)) { |
| 68 | + p <- p + labs(title = label) |
| 69 | + } |
| 70 | + |
| 71 | + return(p) |
| 72 | +} |
0 commit comments