[英]ggplot2 and Shiny: how to scale the size of legend with figure size?
[英]Legend changing the size of ggplot figure in shiny
我在Shiny中有一个ggplot,它使用geom_point绘制一些数据。 我进行了设置,以便在选中复选框时,添加了一种美感,可以将数据着色为两个单独的变量。 这也创建了一个图例。 我的问题是,当出现此图例时,它从图上“占用”了空间,图变得略小。 有没有一种方法可以固定地块的大小,以使图例出现而无需更改地块的大小?
ui <- fluidPage(
titlePanel("Transfers Analysis App"),
sidebarLayout(
sidebarPanel(
checkboxInput("Outage", "Show Outages", FALSE)
),
mainPanel(
plotOutput("plot1", height = "600px", width = "100%", hover = hoverOpts(id = "plot_hover")),
verbatimTextOutput("hover_info")
)
)
)
server <- function(input, output) {
output$plot1 <- renderPlot({
Outage <- input$Outage
g <- ggplot(data, aes(Date, NUMBER_OF_TRANSFERS)) + geom_point()
if (Outage == TRUE)
g <- g + geom_point(aes(color = Outage)) + scale_colour_manual(breaks = c("Outage", "No Outage", "Day After an Outage", "Both"), name= "Legend", values=c( "black", "red", "blue")) + theme(legend.position="bottom")
plot(g)
})
}
shinyApp(ui, server)
注意:我的实际代码中有许多功能比为简单起见而删除的功能要多。
也许有人有更好的主意,但这是一个建议。 您只能绘制同一图形的图例。 您没有提供数据集,所以我以虹膜数据集为例。 如果单击中断,它将在第一个图形的底部显示一个图例。 如果取消单击,将生成您看不到的空白图。 如您所见,图例不会更改第一个图形的大小。
使用本文( 如何仅绘制ggplot2中的图例? ),您可以:
#function to extract the legend
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
ui <- fluidPage(
titlePanel("Transfers Analysis App"),
sidebarLayout(
sidebarPanel(
checkboxInput("Outage", "Show Outages", FALSE)
),
mainPanel(
plotOutput("plot1", height = "600px", width = "100%", hover = hoverOpts(id = "plot_hover")),
plotOutput("plot2"),
verbatimTextOutput("hover_info")
)
)
)
server <- function(input, output) {
output$plot1 <- renderPlot({
Outage <- input$Outage
g <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
if (Outage == TRUE)
g <- g + geom_point(aes(color = Species)) + scale_colour_manual(breaks = c("setosa", "virginica", "versicolor"), values=c( "black", "red", "blue")) +
theme(legend.position="none")
plot(g)
})
output$plot2 <- renderPlot({
Outage <- input$Outage
if (Outage == TRUE) {
g <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
g <- g + geom_point(aes(color = Species)) + scale_colour_manual(breaks = c("setosa", "virginica", "versicolor"), name= "Legend", values=c( "black", "red", "blue")) +
theme(legend.position="bottom") +
theme(legend.text=element_text(size=15)) # you can change the size of the legend
legend <- g_legend(g)
grid.draw(legend)
} else {
g <- ggplot() + theme_bw(base_size=0) +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
plot(g)
}
})
}
shinyApp(ui, server)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.