rggplot2geom-bar

Draw ggplot2 barplot with round corners


I used the "ggchicklet" package to produce rounded stacked bar plots in R. However, this package is no longer available.

On R News page is written "Use ggforce to replace ggchicklet as ggchicklet is not available at CRAN <2024-03-08, Fri>". However, I was unable to generate a desired stacked bar plot. On this page is an example of ggchicklet usage.

Now is available the package ggrounded but only for rounding the top corners.

Are there any suggestions for an alternative for bars with top and base corners rounded? Thanks.


Solution

  • As suggested in the referenced link here is an option to draw rounded bars using ggforce::geom_shape which however requires to transform the data for which I use dplyr::reframe, i.e. similar to the input for a geom_polygon geom_shape requires to specify the coordinates for the four corners of the bar:

    library(ggplot2)
    library(ggforce)
    library(dplyr, warn = FALSE)
    
    df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
    
    width <- .9
    
    df <- df |>
      mutate(trt = factor(trt)) |>
      dplyr::reframe(
        data.frame(
          x = rep(as.numeric(trt) + width / 2 * c(-1, 1), each = 2),
          outcome = c(c(0, outcome), rev(c(0, outcome)))
        ),
        .by = trt
      )
    
    ggplot(df, aes(x, outcome, fill = trt)) +
      geom_shape(radius = .05)