R - Render multiple plots on single page of Shiny

2019-05-21 07:43发布

问题:

I am trying to arrange multiple charts on shiny app. I am trying to plot 2 pie charts and a ggplot2 chart.

require(ggplot2)
require(gridExtra)

par(mfrow = c(2,2))    

z=data.frame(x=1:10, y=11:20)
pie(z$x,z$y)
pie(z$x,z$y)
ggplot(z, aes(x,y)) + geom_bar(stat="identity", width=.3)

I tried with grid.arrange but it only render ggplot chart. I tried to to render these three plot using grid.arrange, then it return error message input must be grobs! Please help to render these three on single page.

回答1:

I'm not certain what you want it to look like but here's an example how to combine your three plots:

require(ggplot2)
require(grid)
require(gridBase)

z=data.frame(x=1:10, y=11:20)

# setup everything
plot.new()
gl <- grid.layout(2,2)
vp.1 <- viewport(layout.pos.col = 1, layout.pos.row = 1)
vp.2 <- viewport(layout.pos.col = 2, layout.pos.row = 1)
vp.3 <- viewport(layout.pos.col = c(1,2), layout.pos.row = 2)
pushViewport(viewport(layout=gl))

# First plot
pushViewport(vp.1)
par(new = TRUE, fig = gridFIG(), mar=c(0,0,0,0))
pie(z$x,z$y)
popViewport()

# Second plot
pushViewport(vp.2)
par(new = TRUE, fig = gridFIG(), mar=c(0,0,0,0))
pie(z$x,z$y)
popViewport(1)

# Your ggplot
pushViewport(vp.3)
p<-ggplot(z, aes(x,y)) + geom_bar(stat="identity", width=.3)
print(p, newpage = FALSE)
popViewport(2)

NOTE: I do not recommend using pie charts. See this example



标签: r plot ggplot2