Reputation: 13
I would like to plot a transformed variable (in this case an average shift value) on the y axis. For the life of me I can't understand how to get R to plot the overall result (not just the calculated sum of each day's average). Any help would be greatly appreciated.
# set up
library(tidyverse)
# example data
df <-
tribble(
~Week, ~Day, ~Team, ~Sales, ~Shifts,
"WK1", 1, "A", 100, 1,
"WK1", 1, "B", 120, 1,
"WK1", 2, "A", 100, 1,
"WK1", 2, "B", 120, 1,
"WK1", 3, "A", 100, 1,
"WK1", 3, "B", 120, 1,
"WK1", 4, "A", 100, 1,
"WK1", 4, "B", 120, 1,
"WK1", 5, "A", 100, 1,
"WK1", 5, "B", 120, 1,
"WK1", 6, "A", 100, 1,
"WK1", 6, "B", 120, 1,
"WK1", 7, "A", 100, 1,
"WK1", 7, "B", 120, 1
)
# P1: y axis is not the shift average as desired. For example, Team A's shift average should be 100.
ggplot(df, aes(x = Week, y = (Sales/Shifts) )) +
geom_col() +
facet_grid(.~ Team)
# P2: ggplot seems to be calculating the sum of each individual day's shift average
ggplot(df, aes(x = Week, y = (Sales/Shifts), fill = Day )) +
geom_col() +
facet_grid(.~ Team)
The overall shift average should be Team A: 100 Team B: 120
Upvotes: 1
Views: 48
Reputation: 146164
I'd recommend summarizing your data and giving ggplot
the values you want to plot, rather than trying to use the graphics package to do the data manipulation for you.
df_avg = df %>%
group_by(Team, Week) %>%
summarize(Shift_Avg = mean(Sales / Shifts))
## or maybe you want sum(Sales) / sum(Shifts) ? Might be more appropriate
ggplot(df_avg, aes(x = Week, y = Shift_Avg)) +
geom_col() +
facet_grid(~ Team)
Upvotes: 1