ggplot bar chart for frequency multiply by sales

Viewed 16

my data has a list of orders consist of order number, product category, number of sales

each order can contain multiple number of sales

I need to create a bar chart of sales by product category , Instead of just counting the number of orders for each product category. I need to count number of orders multiply by their respective number of sales. how do I write the code? thanks

1 Answers

Let´s start with a reproducible example.

library(tidyverrse)

d <- data.frame(category = c(rep("Produt1", 5),rep("Produt2", 5), rep("Produt3", 5)),
                order = round(rnorm(15, 10, 5)),
                sales = round(rnorm(15, 5, 4)))

category order sales

Produt1 13  12      
Produt1 10  7       
Produt1 3   8       
Produt1 12  7       
Produt1 11  1       
Produt2 22  7       
Produt2 9   8       
Produt2 0   3       
Produt2 15  5       
Produt2 13  5

We can aggregate by group, and sum up the results in a new variable called total.

d1 <- d |>
  group_by(category) |>
  summarise(total = sum(order * sales))
  
ggplot() +
 geom_col(data = d1, 
          aes(y = total,
              x = category,
              fill = category)) +
  theme_bw()

Is that what you had in mind?

enter image description here

Related