geom_label不会按比例缩放以在Shiny中绘图

时间:2019-01-27 14:59:35

标签: r ggplot2 shiny

在构建我的Shiny App时,遇到$id = 'tt0159365' ; // example id $c = file_get_contents("https://www.imdb.com/title/$id"); // retrieve the JSON data $d = new DomDocument(); @$d->loadHTML($c); // parse the HTML to retrieve the "ld+json" only $xp = new domxpath($d); $jsonScripts = $xp->query( '//script[@type="application/ld+json"]' ); $json = trim( $jsonScripts->item(0)->nodeValue ); // get the first script only (it should be unique anyway) // decode the JSON string we find into a associative array $data = json_decode( $json, true ); // you can now use this array to query the data you want $duration = $data['duration']; echo "Duration: $duration" ; $director = $data['director']['name'] ; echo "Director : $director" ; 图形在不同窗口大小下看起来非常不同的情况。第一张图以完整的桌面尺寸显示该图-一切正常: enter image description here

但是,当我更改输出窗口的大小时,每个元素似乎都可以正确缩小,但ggplot2却没有(请参见下图)。

enter image description here

为什么会这样?如何使geom_label相应地缩小?

“闪亮”设置为:

geom_label

1 个答案:

答案 0 :(得分:1)

详细的in the shiny documentationsession$client_data$output_<plotname>_width中定义了当前绘图的绘图宽度,因此对于您的示例session$client_data$output_ap_plot_width。这可以用于缩放geom_label的text参数。您没有提供最小的可复制示例,但这是一个示例:

data <- tibble(
  cluster = sample(7, 100, replace = TRUE),
  x = rnorm(100),
  y = rnorm(100)
)

plot_sequences <- function(data_set, width) {
  label_data <- data_set %>% 
    summarise(
      n = n(),
      mean_x = mean(x),
      mean_y = mean(y),
      label = sprintf("N: %d\nMean x: %0.3f\nMean y: %0.3f", n, n, mean_x, mean_y)
    )

  ggplot(data, aes(x, y)) +
    geom_point() +
    geom_label(aes(x = 1.5, y = 1.5, label = label), label_data, size = 4 / 900 * width)
}

ui <- fluidPage(
  mainPanel(
    width = 12,
    selectInput('cluster', '', 1:7),
    plotOutput('ap_plot', height = 200)
  )
)

server <- function(input, output, session) {
  width <- 400
  output$ap_plot <- renderPlot(execOnResize = TRUE, {
    data %>% 
      filter(cluster == input$cluster) %>% 
      plot_sequences(session$clientData[["output_ap_plot_width"]])
  })
}

shinyApp(ui = ui, server = server)

您可以看到我的绘图函数将绘图宽度作为输入,然后使用900像素的宽度作为基线来相应缩放文本大小。还请注意,我将execOnResize设置为TRUE,因为否则将重播绘图,而不是在调整窗口/绘图大小时重新计算。