Aligning the x axis of two plots with different y labels length












2















I have two plots that are located one above the other in a Shiny app.

The two plots have the same x axis, but different y axes.



The width of the x axes is different due to the length of the y axes labels (see image below).
The goal is to align the x axes of the two plots.



Minimal example:



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










share|improve this question


















  • 4





    Will this help stackoverflow.com/a/48164920/786542?

    – Tung
    Nov 18 '18 at 20:45











  • Thanks Tung! It definitely brings me closer. However, I need to use those plots separatly in two different divs. Do you have any idea how can I access them separatly after I'm aligning them? For example, with the patchword package I tried: plots <- p1 + p2 + plot_layout(nrow = 2) and then plots$assemble$plots, but only the first plot was accessible.

    – yanirmor
    Nov 19 '18 at 13:09






  • 1





    Not sure if you can do that but you can give it a try with gtable. See one example here

    – Tung
    Nov 19 '18 at 17:48






  • 1





    Thank you @Tung! The second link was super useful and completely solved the problem. I'll post the solve below

    – yanirmor
    Nov 21 '18 at 19:30











  • my pleasure! well done!

    – Tung
    Nov 21 '18 at 19:58
















2















I have two plots that are located one above the other in a Shiny app.

The two plots have the same x axis, but different y axes.



The width of the x axes is different due to the length of the y axes labels (see image below).
The goal is to align the x axes of the two plots.



Minimal example:



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










share|improve this question


















  • 4





    Will this help stackoverflow.com/a/48164920/786542?

    – Tung
    Nov 18 '18 at 20:45











  • Thanks Tung! It definitely brings me closer. However, I need to use those plots separatly in two different divs. Do you have any idea how can I access them separatly after I'm aligning them? For example, with the patchword package I tried: plots <- p1 + p2 + plot_layout(nrow = 2) and then plots$assemble$plots, but only the first plot was accessible.

    – yanirmor
    Nov 19 '18 at 13:09






  • 1





    Not sure if you can do that but you can give it a try with gtable. See one example here

    – Tung
    Nov 19 '18 at 17:48






  • 1





    Thank you @Tung! The second link was super useful and completely solved the problem. I'll post the solve below

    – yanirmor
    Nov 21 '18 at 19:30











  • my pleasure! well done!

    – Tung
    Nov 21 '18 at 19:58














2












2








2








I have two plots that are located one above the other in a Shiny app.

The two plots have the same x axis, but different y axes.



The width of the x axes is different due to the length of the y axes labels (see image below).
The goal is to align the x axes of the two plots.



Minimal example:



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










share|improve this question














I have two plots that are located one above the other in a Shiny app.

The two plots have the same x axis, but different y axes.



The width of the x axes is different due to the length of the y axes labels (see image below).
The goal is to align the x axes of the two plots.



Minimal example:



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







r ggplot2 shiny






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 18 '18 at 20:37









yanirmoryanirmor

198111




198111








  • 4





    Will this help stackoverflow.com/a/48164920/786542?

    – Tung
    Nov 18 '18 at 20:45











  • Thanks Tung! It definitely brings me closer. However, I need to use those plots separatly in two different divs. Do you have any idea how can I access them separatly after I'm aligning them? For example, with the patchword package I tried: plots <- p1 + p2 + plot_layout(nrow = 2) and then plots$assemble$plots, but only the first plot was accessible.

    – yanirmor
    Nov 19 '18 at 13:09






  • 1





    Not sure if you can do that but you can give it a try with gtable. See one example here

    – Tung
    Nov 19 '18 at 17:48






  • 1





    Thank you @Tung! The second link was super useful and completely solved the problem. I'll post the solve below

    – yanirmor
    Nov 21 '18 at 19:30











  • my pleasure! well done!

    – Tung
    Nov 21 '18 at 19:58














  • 4





    Will this help stackoverflow.com/a/48164920/786542?

    – Tung
    Nov 18 '18 at 20:45











  • Thanks Tung! It definitely brings me closer. However, I need to use those plots separatly in two different divs. Do you have any idea how can I access them separatly after I'm aligning them? For example, with the patchword package I tried: plots <- p1 + p2 + plot_layout(nrow = 2) and then plots$assemble$plots, but only the first plot was accessible.

    – yanirmor
    Nov 19 '18 at 13:09






  • 1





    Not sure if you can do that but you can give it a try with gtable. See one example here

    – Tung
    Nov 19 '18 at 17:48






  • 1





    Thank you @Tung! The second link was super useful and completely solved the problem. I'll post the solve below

    – yanirmor
    Nov 21 '18 at 19:30











  • my pleasure! well done!

    – Tung
    Nov 21 '18 at 19:58








4




4





Will this help stackoverflow.com/a/48164920/786542?

– Tung
Nov 18 '18 at 20:45





Will this help stackoverflow.com/a/48164920/786542?

– Tung
Nov 18 '18 at 20:45













Thanks Tung! It definitely brings me closer. However, I need to use those plots separatly in two different divs. Do you have any idea how can I access them separatly after I'm aligning them? For example, with the patchword package I tried: plots <- p1 + p2 + plot_layout(nrow = 2) and then plots$assemble$plots, but only the first plot was accessible.

– yanirmor
Nov 19 '18 at 13:09





Thanks Tung! It definitely brings me closer. However, I need to use those plots separatly in two different divs. Do you have any idea how can I access them separatly after I'm aligning them? For example, with the patchword package I tried: plots <- p1 + p2 + plot_layout(nrow = 2) and then plots$assemble$plots, but only the first plot was accessible.

– yanirmor
Nov 19 '18 at 13:09




1




1





Not sure if you can do that but you can give it a try with gtable. See one example here

– Tung
Nov 19 '18 at 17:48





Not sure if you can do that but you can give it a try with gtable. See one example here

– Tung
Nov 19 '18 at 17:48




1




1





Thank you @Tung! The second link was super useful and completely solved the problem. I'll post the solve below

– yanirmor
Nov 21 '18 at 19:30





Thank you @Tung! The second link was super useful and completely solved the problem. I'll post the solve below

– yanirmor
Nov 21 '18 at 19:30













my pleasure! well done!

– Tung
Nov 21 '18 at 19:58





my pleasure! well done!

– Tung
Nov 21 '18 at 19:58












1 Answer
1






active

oldest

votes


















1














Using the gtable package solved it (credit to @Tung and his answer).

I converted both of the plots to gtables, and then matched their .$widths.



Here is the working code:



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)
})
}
)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53365201%2faligning-the-x-axis-of-two-plots-with-different-y-labels-length%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Using the gtable package solved it (credit to @Tung and his answer).

    I converted both of the plots to gtables, and then matched their .$widths.



    Here is the working code:



    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)
    })
    }
    )





    share|improve this answer




























      1














      Using the gtable package solved it (credit to @Tung and his answer).

      I converted both of the plots to gtables, and then matched their .$widths.



      Here is the working code:



      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)
      })
      }
      )





      share|improve this answer


























        1












        1








        1







        Using the gtable package solved it (credit to @Tung and his answer).

        I converted both of the plots to gtables, and then matched their .$widths.



        Here is the working code:



        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)
        })
        }
        )





        share|improve this answer













        Using the gtable package solved it (credit to @Tung and his answer).

        I converted both of the plots to gtables, and then matched their .$widths.



        Here is the working code:



        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)
        })
        }
        )






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 19:35









        yanirmoryanirmor

        198111




        198111






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53365201%2faligning-the-x-axis-of-two-plots-with-different-y-labels-length%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to pass form data using jquery Ajax to insert data in database?

            National Museum of Racing and Hall of Fame

            Guess what letter conforming each word