gpt4 book ai didi

r - Shiny :由plotOutput()和/或renderPlot()添加的不需要的空间

转载 作者:行者123 更新时间:2023-12-02 01:36:24 32 4
gpt4 key购买 nike

plotOutput 或 renderPlot 似乎都会在绘图周围添加一堆额外的空白。我已向绘图和布局列添加了背景颜色来说明这一点。本质上,我想完全摆脱这个空白区域,只留下蓝色区域,然后该区域应该与列的左侧对齐。

我知道可以使用 width 参数进行调整,但将其设置为 100%auto 似乎并不适用工作正常。

谢谢!

library(shiny)
library(ggplot2)

# Create sample data
animals <- as.data.frame(
table(Species =
c(rep("Moose", sample(1:100, 1)),
rep("Frog", sample(1:100, 1)),
rep("Dragonfly", sample(1:100, 1))
)))

server <- function(input, output) {

output$pieChart <- renderPlot({

# Create pie chart
ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0) +
theme(plot.background = element_rect(fill = "lightblue"))
})
}

ui <- fluidPage(

fluidRow(
column(4,
style = "background-color:lightgreen",
align = "left",
HTML("filler<br>"),
plotOutput("pieChart")
)
)
)

shinyApp(ui = ui, server = server)

enter image description here

最佳答案

该空间是由网格布局引擎添加的,而不是由任何 Shiny 的东西添加的。 Grid 添加了空白,因为 ggplot 要求它保持绘图的纵横比,以确保圆是圆的。

您可以通过以下方式看到这一点。首先,让我们以常规方式绘制绘图,但首先让我们手动转换为 grob。

g <- ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0) +
theme(plot.background = element_rect(fill = "lightblue"))

library(grid)
grob <- ggplotGrob(g)
grid.newpage()
grid.draw(grob)

这将生成在侧面或上方/下方带有空白的绘图,具体取决于封闭窗口的形状:

enter image description here

enter image description here

现在让我们关闭纵横比强制并再次绘图:

grob$respect <- FALSE # this switches of the fixed aspect ratio
grid.newpage()
grid.draw(grob)

现在没有空白,但圆也不是圆的。

enter image description here

您必须将绘图放入一个封闭的容器中,该容器可以在右侧和底部提供必要的空白。如果您愿意为绘图提供固定大小,则可以使用grid,将绘图放入侧面和底部留有空白空间的表格中:

library(grid)
library(gtable)
# need to play around to find numbers that work
plotwidth = unit(6.1, "inch")
plotheight = unit(5, "inch")

grob <- ggplotGrob(g)
mat <- matrix(list(grob, nullGrob(), nullGrob(), nullGrob()), nrow = 2)
widths <- unit(c(1, 1), "null")
widths[1] <- plotwidth
heights <- unit(c(1, 1), "null")
heights[1] <- plotheight
gm <- gtable_matrix(NULL, mat, widths, heights)
grid.newpage()
grid.draw(gm)

enter image description here

enter image description here

这种方法的缺点是,现在,如果绘图窗口太小,绘图将不会调整大小,而是会被切断:

enter image description here

我不确定如何将绘图缩放到仍然适合窗口的最大可能尺寸。

关于r - Shiny :由plotOutput()和/或renderPlot()添加的不需要的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702624/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com