Search code examples
rplottibblestacked-chart

Stacked bar chart using tibble in R


I have the following tibble df:

`Region`    `Product`    `Cost`
 <fct>       <fct>        <dbl>
 1 Japan     Laptop       1500
 2 Egypt     Printer      450
 ...

and I would like to create a stacked barplot with Region on the x-axis, and the each column being the sum of all the costs in that region broken down into Product categories (i.e. a stack of total costs per product for the given region.)

I have unsuccessfully tried the following:

ggplot(df, aes(x = "Region", y = "Cost")) + geom_col(aes(fill = "Product"))

Could someone please help me out? Thanks!


Solution

  • If you pass variable names in quoted format as string, it considers that as value to plot. In ggplot2 syntax to refer to a column you have to pass them as unquoted variables. So try :

    library(ggplot2)
    ggplot(df, aes(x = Region, y = Cost)) + geom_col(aes(fill = Product))