将两个图的x轴与y标签长度不同

时间:2018-11-18 20:37:24

标签: r ggplot2 shiny

我在Shiny应用程序中有两个地块位于另一个地块上。
这两个图具有相同的x轴,但具有不同的y轴。

由于y轴标签的长度,x轴的宽度不同(请参见下图)。
目标是对齐两个图的x轴。

最小示例:

library(shiny)
library(ggplot2)

df <- data.frame(
  stringsAsFactors = F,
  date = as.Date.factor(c("2010-01-01", "2011-01-01", "2012-01-01")),
  var1 = c(1000000, 2000000, 1500000),
  var2 = c(10, 15, 20)
)

shinyApp(
  ui = fluidPage(
    fluidRow(column(4, offset = 4, plotOutput(outputId = "plot1"))),
    fluidRow(column(4, offset = 4, plotOutput(outputId = "plot2")))
  ),
  server = function(input, output, session) {
    output$plot1 <- renderPlot(
      ggplot(data = df, mapping = aes(x = date, y = var1)) + 
        geom_line() +
        scale_x_date(breaks = df$date)
    )

    output$plot2 <- renderPlot(
      ggplot(data = df, mapping = aes(x = date, y = var2)) + 
        geom_bar(stat = "identity") +
        scale_x_date(breaks = df$date)
    )
  }
)

enter image description here

1 个答案:

答案 0 :(得分:1)

使用gtable软件包解决了该问题(贷记@Tung和他的answer)。
我将两个图都转换为gtables,然后匹配了它们的.$widths

这是工作代码:

library(shiny)
library(ggplot2)
library(grid)
library(gtable)

df <- data.frame(
  stringsAsFactors = F,
  date = as.Date.factor(c("2010-01-01", "2011-01-01", "2012-01-01")),
  var1 = c(1000000, 2000000, 1500000),
  var2 = c(10, 15, 20)
)

shinyApp(
  ui = fluidPage(
    fluidRow(column(4, offset = 4, plotOutput(outputId = "plot1"))),
    fluidRow(column(4, offset = 4, plotOutput(outputId = "plot2")))
  ),
  server = function(input, output, session) {
    p1_widths <- reactiveVal(value = NULL)

    output$plot1 <- renderPlot({
      p <- ggplot(data = df, mapping = aes(x = date, y = var1)) + 
        geom_line() +
        scale_x_date(breaks = df$date, expand = c(0, 200.75))

      g <- ggplot_gtable(data = ggplot_build(plot = p))
      p1_widths(g$widths)

      grid.draw(g)
    })

    output$plot2 <- renderPlot({
      p <- ggplot(data = df, mapping = aes(x = date, y = var2)) + 
        geom_bar(stat = "identity") +
        scale_x_date(breaks = df$date, expand = c(0, 36.5))

      g <- ggplot_gtable(data = ggplot_build(plot = p))
      g$widths <- p1_widths()

      grid.draw(g)
    })
  }
)