【问题标题】:How to use max of a variable in title/subtitle of a plot with glue in r?如何在 r 中使用胶水在绘图的标题/副标题中使用变量的最大值?
【发布时间】:2020-12-12 19:36:10
【问题描述】:

我有一个用户定义的函数,可以计算给定国家/地区的每日新冠病例并给出一个数据框:


fn_daily_cases <- function(Country_Name = India)
  {
  Country_Name <- rlang::quo_name(rlang::enquo(Country_Name))
  # above line will insert quote to the value in variable Country_Name
  
  df_gather %>% filter(Country.Region == Country_Name) %>% 
    mutate(daily_cases = abs(Cases_Count - lag(Cases_Count, default = 0))) %>% 
    # at beginning it will give 0 instead of NA
    
    arrange(desc(Date))
  
  } 

fn_daily_cases(Spain)

####### output ########

Country.Region Date   Cases_Count daily_cases
<chr>          <date> <int>       <dbl>

Spain   2020-12-11  1730575 10519   
Spain   2020-12-10  1720056 7955    
Spain   2020-12-09  1712101 9773    
Spain   2020-12-08  1702328 0   
Spain   2020-12-07  1702328 17681   
Spain   2020-12-06  1684647 0   
Spain   2020-12-05  1684647 0   
Spain   2020-12-04  1684647 8745    
Spain   2020-12-03  1675902 10127   
Spain   2020-12-02  1665775 9331    

问题:当我尝试使用另一个函数绘制此数据框时,我无法在 subtitle

中显示 max( Cases_Count)
library(glue)
library(tidyverse)

fn_daily_cases_plot <- function(country_selected = India) {
  
  fn_daily_cases({{country_selected}}) %>% 
  ggplot(aes(Date, y = daily_cases)) +
  geom_line(col = "midnightblue") +
  labs(title = glue("{quo_name(enquo(country_selected))} Daily Cases") ,
       subtitle = glue("Total cases so far: {max(Cases_Count)}" )
       ) +
  theme_light()
}

fn_daily_cases_plot(Spain)


##### output ######

Error in eval(parse(text = text, keep.source = FALSE), envir) : object 'Cases_Count' not found

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

    尝试先将数据保存在单独的tibblex,然后调用 max(x$Cases_Count).

    fn_daily_cases_plot <- function(country_selected = India) {
    
      x <- fn_daily_cases({{country_selected}})
    
      ggplot(x, aes(Date, y = daily_cases)) + 
      geom_line(col = "midnightblue") +
      labs(title = glue("{quo_name(enquo(country_selected))} Daily Cases") , 
            subtitle = glue("Total cases so far: {max(x$Cases_Count)}" )) +
      theme_light() 
    }
    

    无论如何,我不知道您为什么更喜欢 glue 而不是基本替代品 paste (另见this question)。

    【讨论】:

    • 感谢@Cettt,我不明白为什么将其分配给 x & 然后分配给 max(x$Cases_Count) 但它不适用于 max(.$Cases_Count)。很多时候我不明白 R tidyverse 管道是如何工作的。在许多情况下,.$variable 有效,但有时无效,因此它对我来说仍然是一种热门和试用方法。我是 R 的新手,有些人在之前的一些其他问题中已经展示了带有glue() 的示例,所以我开始使用glue() 而不是sprintf。
    • magrittr 管道 %&gt;% 将 rhs 解释为函数并在 lhs 中计算 at。在您的代码版本中,您只使用一个管道:在 lhs 上有一个数据框,在 rhs 上有一个 ggplot 函数调用。所以 R 根据数据框中的信息绘制了一个图。如果您想将 lhs 放在 rhs 调用中的其他位置,我建议您阅读帮助站点(参见 ?%&gt;%)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多