2015-12-14 516 views
10

在ggplot2中,元素的大小是分開指定的。當圖形大小改變時,元素(例如圖例)不會改變。當輸出ggplot2數字的大小隨瀏覽器窗口變化時,這可能是Shiny中的一個問題。下面是一個虛擬Shiny應用程序的代碼和兩個不同瀏覽器窗口大小的輸出數字。由於其傳奇的一部分已被切斷,因此較小的數字很難看。ggplot2和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

回答

8

這裏有一個方式來錨定圖例的頂部,以便它不會跑出劇情區域的頂部。您只需將legend.justification(0.5, 1)添加到ggplot theme即可。第一個值以圖例的x位置爲中心。第二個值「top justify」圖例的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

+0

感謝。這使得數字更好。 –