我有一个像这样的data.frame.

library(tidyverse)
library(gghighlight)

# this works
df <- 
  tibble::tribble(
             ~year, ~sales_rep, ~sale_count,
              2021,        "1",         615,
              2021,        "2",         246,
              2021,        "3",         245,
              2022,        "1",         736,
              2022,        "2",          56,
              2022,        "3",         868,
              2023,        "1",         452,
              2023,        "2",         185,
              2023,        "3",         915
  )

我想画出每个销售代表的销售额,并用gghighlight来提醒大家注意销售代表1.

df %>% 
  ggplot(
    aes(
      x = year,
      y = sale_count,
      fill = sales_rep
    )
  ) +
  geom_col() +
  facet_wrap(
    vars(sales_rep)
  ) +
  gghighlight(sales_rep == 1, calculate_per_facet = TRUE)
#> Warning: Tried to calculate with group_by(), but the calculation failed.
#> Falling back to ungrouped filter operation...

然而,当我试图添加一个geom_hline来显示每个销售代表的平均年销售额时,gghighlight抛出了一个错误.

# but this doesn't
avg_by_rep <- 
  df %>% 
  summarize(
    avg_sales = mean(sale_count),
    .by = sales_rep
  )

df %>% 
  ggplot(
    aes(
      x = year,
      y = sale_count,
      fill = sales_rep
    )
  ) +
  geom_col() +
  geom_hline(
    data = avg_by_rep,
    aes(
      yintercept = avg_sales
    )
  ) +
  facet_wrap(
    vars(sales_rep)
  ) +
  gghighlight(sales_rep == 1, calculate_per_facet = TRUE)
#> New names:
#> * `highlight..........1` -> `highlight.......`
#> Warning: Tried to calculate with group_by(), but the calculation failed.
#> Falling back to ungrouped filter operation...
#> Error in `geom_hline()`:
#> ! Problem while computing aesthetics.
#> i Error occurred in the 2nd layer.
#> Caused by error in `FUN()`:
#> ! object 'highlight..........1' not found
#> Backtrace:
#>      x
#>   1. +-base::tryCatch(...)
#>   2. | \-base (local) tryCatchList(expr, classes, parentenv, handlers)
#>   3. |   +-base (local) tryCatchOne(...)
#>   4. |   | \-base (local) doTryCatch(return(expr), name, parentenv, handler)
#>   5. |   \-base (local) tryCatchList(expr, names[-nh], parentenv, handlers[-nh])
#>   6. |     \-base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
#>   7. |       \-base (local) doTryCatch(return(expr), name, parentenv, handler)
#>   8. +-base::withCallingHandlers(...)
#>   9. +-base::saveRDS(...)
#>  10. +-base::do.call(...)
#>  11. +-base (local) `<fn>`(...)
#>  12. +-global `<fn>`(input = base::quote("large-unau_reprex.R"))
#>  13. | \-rmarkdown::render(input, quiet = TRUE, envir = globalenv(), encoding = "UTF-8")
#>  14. |   \-knitr::knit(knit_input, knit_output, envir = envir, quiet = quiet)
#>  15. |     \-knitr:::process_file(text, output)
#>  16. |       +-base::withCallingHandlers(...)
#>  17. |       +-knitr:::process_group(group)
#>  18. |       \-knitr:::process_group.block(group)
#>  19. |         \-knitr:::call_block(x)
#>  20. |           \-knitr:::block_exec(params)
#>  21. |             \-knitr:::eng_r(options)
#>  22. |               +-knitr:::in_input_dir(...)
#>  23. |               | \-knitr:::in_dir(input_dir(), expr)
#>  24. |               \-knitr (local) evaluate(...)
#>  25. |                 \-evaluate::evaluate(...)
#>  26. |                   \-evaluate:::evaluate_call(...)
#>  27. |                     +-evaluate (local) handle(...)
#>  28. |                     | \-base::try(f, silent = TRUE)
#>  29. |                     |   \-base::tryCatch(...)
#>  30. |                     |     \-base (local) tryCatchList(expr, classes, parentenv, handlers)
#>  31. |                     |       \-base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
#>  32. |                     |         \-base (local) doTryCatch(return(expr), name, parentenv, handler)
#>  33. |                     +-base::withCallingHandlers(...)
#>  34. |                     +-base::withVisible(value_fun(ev$value, ev$visible))
#>  35. |                     \-knitr (local) value_fun(ev$value, ev$visible)
#>  36. |                       \-knitr (local) fun(x, options = options)
#>  37. |                         +-base::withVisible(knit_print(x, ...))
#>  38. |                         +-knitr::knit_print(x, ...)
#>  39. |                         \-knitr:::knit_print.default(x, ...)
#>  40. |                           \-evaluate (local) normal_print(x)
#>  41. |                             +-base::print(x)
#>  42. |                             \-ggplot2:::print.ggplot(x)
#>  43. |                               +-ggplot2::ggplot_build(x)
#>  44. |                               \-ggplot2:::ggplot_build.ggplot(x)
#>  45. |                                 \-ggplot2:::by_layer(...)
#>  46. |                                   +-rlang::try_fetch(...)
#>  47. |                                   | +-base::tryCatch(...)
#>  48. |                                   | | \-base (local) tryCatchList(expr, classes, parentenv, handlers)
#>  49. |                                   | |   \-base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
#>  50. |                                   | |     \-base (local) doTryCatch(return(expr), name, parentenv, handler)
#>  51. |                                   | \-base::withCallingHandlers(...)
#>  52. |                                   \-ggplot2 (local) f(l = layers[[i]], d = data[[i]])
#>  53. |                                     \-l$compute_aesthetics(d, plot)
#>  54. |                                       \-ggplot2 (local) compute_aesthetics(..., self = self)
#>  55. |                                         \-base::lapply(aesthetics, eval_tidy, data = data, env = env)
#>  56. |                                           \-rlang (local) FUN(X[[i]], ...)
#>  57. \-base::.handleSimpleError(...)
#>  58.   \-rlang (local) h(simpleError(msg, call))
#>  59.     \-handlers[[1L]](cnd)
#>  60.       \-cli::cli_abort(...)
#>  61.         \-rlang::abort(...)

创建于2024-01-15年第reprex v2.0.2

推荐答案

记住要放gghighlight before geom_hline(我也会加上use_group_by = FALSE来删除警告.

ggplot(df, aes(x = year, y = sale_count, fill = sales_rep)) +
  geom_col() +
  facet_wrap(vars(sales_rep)) +
  gghighlight(sales_rep == 1, calculate_per_facet = TRUE, 
              use_group_by = FALSE) +
  geom_hline(aes(yintercept = y_i),
             data = summarise(df, y_i = mean(sale_count), .by = sales_rep))

enter image description here

当然,在这个特定的场景中,我们可以得到类似的结果,而根本不使用gghighlight.

ggplot(df, aes(x = year, y = sale_count)) +
  geom_col(aes(fill = ifelse(sales_rep == "1", "1", NA))) +
  scale_fill_discrete("Sales rep", breaks = "1", na.value = "#80808080") +
  facet_wrap(vars(sales_rep)) +
  geom_hline(aes(yintercept = y_i),
             data = summarise(df, y_i = mean(sale_count), .by = sales_rep)) 

enter image description here

R相关问答推荐

将Multilinetring合并到一个线串中,使用sf生成规则间隔的点

多个ggpredicate对象的平均值

提取R中值和列名的所有可能组合

如何删除R中除某些特定名称外的所有字符串?

根据R中两个变量的两个条件删除带有dspirr的行

如何求解arg必须为NULL或deSolve包的ode函数中的字符向量错误

用derrr在R中查找组间的重复项

为什么横向页面会导致officeverse中的页码/节头/页脚出现问题?

修改用R编写的用户定义函数

R中的哈密顿滤波

您是否可以折叠R中的重复行,同时保留基于所选列的值?

按多列统计频次

更新R中的数据表(使用data.table)

变长向量的矢量化和

数值型数据与字符混合时如何进行绑定

变异以按组从其他列创建具有最大和最小值的新列

禁用时,SelecizeInput将变得不透明

如何在刻面和翻转堆叠条形图中对齐geom_text()

在REST API中使用参数R

如何将字符类对象中的数据转换为R中的字符串