R中具有相似结构的多个高图

Multiple highchart with similar structure in R

我的 shiny 应用程序中有多个 highcharts,它们的结构都相似,所以我尝试使用一个函数来概括:

  1. 在我的数据文件中:

编辑

set.seed(5)      
data <- data.frame(id=1:10, 
               period=seq(2011,2020, 1),
               program=rep(LETTERS[1:2], 5),
               total=rnorm(10))
    gral <- function(df,x,y,group,theme){
    highchart() %>%
      hc_xAxis(type = "category") %>%
      hc_add_series(df, "line",
                    hcaes(x = x, y = y
                          ,group = group),
                    dataLabels = list(enabled = TRUE,
                                      style = list(fontSize = '13px'))
      ) %>% 
      hc_legend(enabled = TRUE) %>% 
      hc_tooltip(shared = TRUE, crosshairs = TRUE
                 ,style = list(fontSize = "18px")
      ) %>%
      hc_add_theme(theme) }
  1. 在我的服务器文件中(每个图表)
      output$usuariosgral <- renderHighchart({  gral(df = data, x = period, y = total,
      group = program, theme = hc_theme_elementary()) })

但是它不起作用,有人知道为什么吗?

终于在这里找到了答案,万一对大家有用 -->

只需要使用库 rlang 中的函数 ensym。所以在我的代码中,将 hcaes 行更改为:

hcaes(x = !!rlang::ensym(x), y = !!rlang::ensym(y), group = !!rlang::ensym(group))

这是一个常见问题:hcaes 基于 ggplot2::aes 并且行为相似,幸运的是,您可以将其作为字符串访问,ggplot2aes_string 并且highcharter 有 hcaes_string

library(shiny)
library(highcharter)

gral  <- function(df,x,y,group,theme){
    highchart() %>%
        hc_xAxis(type = "category") %>%
        hc_add_series(df, "line",
                      hcaes_string(x = x, y = y, group = group),
                      dataLabels = list(enabled = TRUE,
                                        style = list(fontSize = '13px'))) %>% 
        hc_legend(enabled = TRUE) %>% 
        hc_tooltip(shared = TRUE, crosshairs = TRUE,style = list(fontSize = "18px")) %>%
        hc_add_theme(theme) 
}

ui <- basicPage(
    column(12,
           highchartOutput('usuariosgral')
    )
)

server <- function(input, output, session) {
    
    output$usuariosgral <- renderHighchart({  
        gral(df = mtcars,x ='mpg',y = 'disp',group ='cyl',theme = hc_theme_elementary())
    })
    
}

shinyApp(ui, server)

我找到了答案 以防对任何人有用。

只需要使用库 rlang 中的函数 ensym。所以在我的代码中,将 hcaes 行更改为:

hcaes(x = !!rlang::ensym(x), y = !!rlang::ensym(y), group = !!rlang::ensym(group))