ash bounty
ash bounty

Reputation: 227

Average sales per weekday with ggplot2

I have some transaction data for two years that I want to analyse in R. It has the following structure:

date                   weekday  salesval
1 2003-10-31           Mi        425.36
2 2003-10-31           Mi       1504.50
3 2003-10-31           Mi        170.14
4 2002-03-12           Mo       -215.80
5 2002-02-08           Mi          0.00
6 2002-04-17           Do        215.80

I want to illustrate the average amount of total sales per weekday by using the ggplot2 graphic system.

I have tried this by using the stat_summary function but as you can see, my approach only calculates the average sales value per transaction per weekday. But I want the average total sales per weekday.

ggplot(data, aes(weekday, salesval)) + 
    stat_summary(fun.y = function(x) { sum(x) / length(x) }, geom = "bar") +
    scale_y_continuous(labels = dollar) +
    ylab("Sales") +
    xlab("Weekday") +
    ggtitle("Average Sales per Weekday")

enter image description here

I know what is wrong with my code, but I have no idea how to achieve my actual goal.

Hope somebody can help me.

Best wishes, Marcus

Upvotes: 0

Views: 935

Answers (3)

Dan Valle
Dan Valle

Reputation: 31

Another option is to build your dataset first and then plot:

library(dplyr)
data1 <- data %>% 
  group_by(weekday) %>%
  summarise(salesval = mean(salesval)) 

a <- ggplot(data1, aes(weekday, salesval)) + 
  geom_bar(stat='identity')

a

Upvotes: 0

Sandipan Dey
Sandipan Dey

Reputation: 23129

With dplyr

library(dplyr)
df %>% group_by(weekday) %>% summarise(salesval=mean(salesval)) %>% 
  ggplot(aes(weekday, salesval)) + geom_bar(stat='identity')

enter image description here

Upvotes: 0

user7396508
user7396508

Reputation:

You could provide an aggregating function as the data

ggplot(data = aggregate(df$salesval, list(df$weekday), mean), aes(Group.1, x)) +
     geom_col()

Based on the sample data, that would create this

Upvotes: 2

Related Questions