2015-12-14 28 views
10

ggplot2では、要素のサイズが別々に指定されています。 Figureのサイズが変わると、凡例などの要素は変更されません。これは、出力ggplot2のサイズがブラウザのウィンドウで変更されたときのShinyの問題です。以下は、ダミーShinyアプリのコードと異なるブラウザウィンドウサイズでの2つの出力数値です。伝説の一部が断絶されているため、小さな数字は醜いです。ggplot2とShiny:凡例のサイズをフィギュアサイズでスケールする方法は?

Shinyアプリの画像ファイルとして図を事前に保存せずに、ggplot2で図形サイズの凡例サイズを直接拡大縮小する方法はありますか?

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

をここです凡例の上部をアンカーして、プロット領域の上部からはみ出さないようにします。 ggplot themelegend.justification(0.5, 1)を追加するだけです。最初の値は、凡例のx位置を中心にします。第2の値は、凡例の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

感謝。これにより、数字がはるかに良くなります。 –

関連する問題