stacked bar plot for sales plot

32 Views Asked by At

I'm trying to create a stacked bar plot for the total sales of each item in each category using R, my dataframe looks like:

category item amount
Accessories Backpack 59507
Accessories Handbag 61047
Clothing Blouse 71029
Footwear Boots 62363

This is the code I have:

ggplot(sales_amount, aes(fill = item, y = amount, x = category)) +
  geom_bar(stat = "identity", position = "stack", width = 0.6) +
  labs(title = "Sales Total for Each Item Within Each Category", x = "Category", y = "Sales Total")+
  scale_y_continuous(labels = scales::comma) +
  coord_flip()

and I got the bar plot looks like this:

The total amount is correct, however, the proportional of the subcategory is wrong. I figured its because it shows the number of times each item appears in the table. How to change my code to make the bar plot showing the sales amount of each items? looks like this?(chatgpt generated it)

1

There are 1 best solutions below

0
Josep Pueyo On

I created a synthetic dataframe trying to reproduce yours. I don't know what was wrong with your code but this seems to work:

library(dplyr)
library(ggplot2)

sales_amount <- tibble(
  category = sample(LETTERS[1:3], 100, replace = TRUE),
  item = sample(letters[1:10], 100, replace = TRUE),
  amount = runif(100, 1000, 10000)
) |> 
  distinct(category, item, .keep_all = TRUE)

sales_amount |>
  ggplot(aes(fill = item, y = amount, x = category)) +
  geom_col(width = 0.6) +
  labs(title = "Sales Total for Each Item Within Each Category", x = "Category", y = "Sales Total")+
  scale_y_continuous(labels = scales::comma) +
  coord_flip()

Created on 2024-03-21 with reprex v2.1.0