如何正确地将转换后的变量添加到ggplot轴

时间:2019-07-08 13:13:42

标签: r ggplot2

我想在y轴上绘制一个转换后的变量(在这种情况下为平均移位值)。在我的一生中,我无法理解如何使用R来绘制总体结果(而不仅仅是每天平均值的计算得出的总和)。任何帮助将不胜感激。

# 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)

总体平均移位应为 A队:100 乙组:120

1 个答案:

答案 0 :(得分:1)

我建议汇总您的数据并为ggplot提供要绘制的值,而不要尝试使用图形包为您进行数据处理。

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)

enter image description here