ggplot2和Shiny:如何缩放图形大小的图例大小?
问题描述:
在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)
但在小的浏览器窗口,传说的顶部没有显示出来:
答
这里有一个方式来锚定图例的顶部,以便它不会跑出剧情区域的顶部。您只需将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)
}
)
}
下面我插入了在“小”和“大”浏览器窗口中显示内容的图像。
感谢。这使得数字更好。 –