r - ggplot2 和 Shiny 的 : how to scale the size of legend with figure size?

标签 r ggplot2 shiny

在 ggplot2 中,元素的大小是单独指定的。当图形的大小发生变化时,元素(例如图例)不会发生变化。当输出 ggplot2 图形的大小随浏览器窗口变化时,这可能是 Shiny 中的一个问题。下面是一个虚拟的 Shiny 应用程序和两个不同浏览器窗口大小的输出数字的代码。较小的数字很难看,因为其传说的一部分已被切断。

有没有一种方法可以直接在 ggplot2 中使用图形大小缩放图例大小,而无需将图形预先保存为 Shiny 应用程序的图像文件?

library(shiny)
library(ggplot2)

ui <- fluidPage(
    br(), br(), br(),
    plotOutput("test", height = "auto")
)

server <- function(input, output, session) {
    output$test <- renderPlot(
        height = function() {
            0.8 * session$clientData$output_test_width
        },
        expr = {
            aaa <- ggplot(mtcars, aes(wt, mpg, color = cyl)) + 
                geom_point() + 
                theme(legend.position = c(0.9, 0.9))
            print(aaa)
        }
    )
}

shinyApp(ui, server)

较大浏览器窗口中的图看起来不错:
enter image description here

但是在小的浏览器窗口中,图例的顶部没有显示:

enter image description here

最佳答案

这是一种 anchor 定图例顶部的方法,这样它就不会超出绘图区域的顶部。您只需添加 legend.justification(0.5, 1)到 ggplot theme .第一个值将图例的 x 位置居中。第二个值“顶部对齐”图例的 y 位置。 (您可以通过将第一个值的 0.5 更改为 1 来右对齐图例,这将防止图例从图形的右边缘运行,如果这是一个问题。)这并不能解决相对大小问题,但是完整的图例将始终可见且位于同一位置。

server <- function(input, output, session) {
  output$test <- renderPlot(
    height = function() {
      0.8 * session$clientData$output_test_width
    },
    expr = {
      aaa <- ggplot(mtcars, aes(wt, mpg, color = cyl)) + 
        geom_point() + 
        theme(legend.position = c(0.9, 0.98),
              legend.justification=c(0.5, 1))
      print(aaa)
    }
  )
}

下面我插入了“小”和“大”浏览器窗口中的图像。

enter image description here

enter image description here

关于r - ggplot2 和 Shiny 的 : how to scale the size of legend with figure size?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274531/

相关文章:

r - 为什么 5 == 3|7 在 R 中是 TRUE

r - 在不同 axis.title/text 属性的情况下调整面板图 (ggplot) 子图之间的间距

r - NA 作为 aes_string 中的输入

r - 将 R Shiny 应用程序保存为函数,并将参数传递给 Shiny 的应用程序

r - 如何在 ggplot 中注释图框之外的图?

R auto.arima 错误

r - 如何在黄土和样条回归中添加协变量,然后使用 ggplot2 在 r 中绘制它

r - 在同一张图中绘制具有多个值的分布图

r - 如何将 html_widget 中的屏幕截图复制为 png

html - 在 R shiny 中创建 HTML 表格