【问题标题】:ggplot2 and Shiny: how to scale the size of legend with figure size?ggplot2 和 Shiny:如何用图形大小缩放图例的大小?
【发布时间】:2016-03-20 09:01:56
【问题描述】:

在 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)

大浏览器窗口中的图看起来不错:

但在小浏览器窗口中,图例顶部不显示:

【问题讨论】:

    标签: r ggplot2 shiny


    【解决方案1】:

    这是一种锚定图例顶部的方法,这样它就不会超出情节区域的顶部。您只需将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)
        }
      )
    }
    

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

    【讨论】:

    • 谢谢。这使数字更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    相关资源
    最近更新 更多