ggplot2 increase space between legend keys












43















How can I increase the space between the keys of the legend of ggplot2 plot?



library(ggplot2)
ggplot(aes(mpg, wt, colour = factor(cyl)),
, data = mtcars) +
geom_point() +
theme(legend.direction = "horizontal",
legend.position = "bottom") +
guides(color = guide_legend(nrow=2))


enter image description here



I am looking for a ggplot2 option that add a kind of vertical adjustment between (key 4 and key 6) in the plot above? Should I create a custom legend key?



PS: I want to increase the blank space between boxes not between labels.



the desired plot is :



enter image description here



NOTE: No the question is not duplicated of the other question. We want here to add a vertical spacing between items that are already in multiple rows. In the other question we have 1-row legend and we want to add spaces (horizontal) between items.










share|improve this question




















  • 1





    Possible duplicate of this. Did that solve your issue?

    – Heroka
    Aug 28 '15 at 15:58











  • @Heroka no.it is not a duplicate.I don't want to change the key size. just the space between the keys. You can try the solution in the link to check this.

    – agstudy
    Aug 28 '15 at 15:59













  • grid or gridExtra might help, I've never used them much though... The gridExtra vignette looks somewhat promising, but is far from giving a clear solution.

    – maj
    Aug 28 '15 at 16:42


















43















How can I increase the space between the keys of the legend of ggplot2 plot?



library(ggplot2)
ggplot(aes(mpg, wt, colour = factor(cyl)),
, data = mtcars) +
geom_point() +
theme(legend.direction = "horizontal",
legend.position = "bottom") +
guides(color = guide_legend(nrow=2))


enter image description here



I am looking for a ggplot2 option that add a kind of vertical adjustment between (key 4 and key 6) in the plot above? Should I create a custom legend key?



PS: I want to increase the blank space between boxes not between labels.



the desired plot is :



enter image description here



NOTE: No the question is not duplicated of the other question. We want here to add a vertical spacing between items that are already in multiple rows. In the other question we have 1-row legend and we want to add spaces (horizontal) between items.










share|improve this question




















  • 1





    Possible duplicate of this. Did that solve your issue?

    – Heroka
    Aug 28 '15 at 15:58











  • @Heroka no.it is not a duplicate.I don't want to change the key size. just the space between the keys. You can try the solution in the link to check this.

    – agstudy
    Aug 28 '15 at 15:59













  • grid or gridExtra might help, I've never used them much though... The gridExtra vignette looks somewhat promising, but is far from giving a clear solution.

    – maj
    Aug 28 '15 at 16:42
















43












43








43


5






How can I increase the space between the keys of the legend of ggplot2 plot?



library(ggplot2)
ggplot(aes(mpg, wt, colour = factor(cyl)),
, data = mtcars) +
geom_point() +
theme(legend.direction = "horizontal",
legend.position = "bottom") +
guides(color = guide_legend(nrow=2))


enter image description here



I am looking for a ggplot2 option that add a kind of vertical adjustment between (key 4 and key 6) in the plot above? Should I create a custom legend key?



PS: I want to increase the blank space between boxes not between labels.



the desired plot is :



enter image description here



NOTE: No the question is not duplicated of the other question. We want here to add a vertical spacing between items that are already in multiple rows. In the other question we have 1-row legend and we want to add spaces (horizontal) between items.










share|improve this question
















How can I increase the space between the keys of the legend of ggplot2 plot?



library(ggplot2)
ggplot(aes(mpg, wt, colour = factor(cyl)),
, data = mtcars) +
geom_point() +
theme(legend.direction = "horizontal",
legend.position = "bottom") +
guides(color = guide_legend(nrow=2))


enter image description here



I am looking for a ggplot2 option that add a kind of vertical adjustment between (key 4 and key 6) in the plot above? Should I create a custom legend key?



PS: I want to increase the blank space between boxes not between labels.



the desired plot is :



enter image description here



NOTE: No the question is not duplicated of the other question. We want here to add a vertical spacing between items that are already in multiple rows. In the other question we have 1-row legend and we want to add spaces (horizontal) between items.







r ggplot2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 28 '15 at 17:31







agstudy

















asked Aug 28 '15 at 15:55









agstudyagstudy

98.6k11144203




98.6k11144203








  • 1





    Possible duplicate of this. Did that solve your issue?

    – Heroka
    Aug 28 '15 at 15:58











  • @Heroka no.it is not a duplicate.I don't want to change the key size. just the space between the keys. You can try the solution in the link to check this.

    – agstudy
    Aug 28 '15 at 15:59













  • grid or gridExtra might help, I've never used them much though... The gridExtra vignette looks somewhat promising, but is far from giving a clear solution.

    – maj
    Aug 28 '15 at 16:42
















  • 1





    Possible duplicate of this. Did that solve your issue?

    – Heroka
    Aug 28 '15 at 15:58











  • @Heroka no.it is not a duplicate.I don't want to change the key size. just the space between the keys. You can try the solution in the link to check this.

    – agstudy
    Aug 28 '15 at 15:59













  • grid or gridExtra might help, I've never used them much though... The gridExtra vignette looks somewhat promising, but is far from giving a clear solution.

    – maj
    Aug 28 '15 at 16:42










1




1





Possible duplicate of this. Did that solve your issue?

– Heroka
Aug 28 '15 at 15:58





Possible duplicate of this. Did that solve your issue?

– Heroka
Aug 28 '15 at 15:58













@Heroka no.it is not a duplicate.I don't want to change the key size. just the space between the keys. You can try the solution in the link to check this.

– agstudy
Aug 28 '15 at 15:59







@Heroka no.it is not a duplicate.I don't want to change the key size. just the space between the keys. You can try the solution in the link to check this.

– agstudy
Aug 28 '15 at 15:59















grid or gridExtra might help, I've never used them much though... The gridExtra vignette looks somewhat promising, but is far from giving a clear solution.

– maj
Aug 28 '15 at 16:42







grid or gridExtra might help, I've never used them much though... The gridExtra vignette looks somewhat promising, but is far from giving a clear solution.

– maj
Aug 28 '15 at 16:42














2 Answers
2






active

oldest

votes


















51














An alternative (and probably easier) solution is using legend.key and legend.key.size in the theme part of your code:



ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
geom_point() +
guides(color = guide_legend(nrow = 2)) +
theme(legend.direction = 'horizontal',
legend.position = 'bottom',
legend.key = element_rect(size = 5),
legend.key.size = unit(1.5, 'lines'))


this gives:



enter image description here





In case you are calling theme_bw or theme_classic before manipulating the legend, you should set the color of the legend rectangle:



legend.key = element_rect(size = 5, color = 'white') #or: color = NA





share|improve this answer


























  • Could you explain the difference between the size property of legend.key and the lines property of legend.key.size. Which one controls the spacing between the keys (i.e., the grey boxes + the label)?

    – Berk U.
    Jun 2 '16 at 21:20











  • @BerkU. The size parameter of legend.key determines the size of the boundary line. The lines property of legend.key.size determines the size of the whole box.

    – Jaap
    Jun 19 '16 at 16:34











  • This did not solve my situation, because the lines made some legend symbols increase together with the box. In my situation, the point symbol did not increase (same as your example) but the line symbol did. As my lines were vertical, the box kept getting taller as lines was increased, without increasing the space between the two columns of the legend. Will report back if I find a solution.

    – PatrickT
    Sep 30 '17 at 12:46






  • 1





    @PatrickT Not sure what your problem is. Maybe post as a new question?

    – Jaap
    Sep 30 '17 at 16:59











  • @Jaap, The problem came to bite me again and I couldn't remember if I had resolved it last time around (see my comment on 30 Sep 2017), so I posted a question: stackoverflow.com/questions/49668265/…

    – PatrickT
    Apr 5 '18 at 9:04



















8














Here a solution using gtable. Basically I am extracting legend grobs table and I add a row in the legend table.



library(gtable)
library(grid)
## transform the ggplot to a grobs table
p_table <- ggplot_gtable(ggplot_build(p))
## extract legend
leg <- which(sapply(p_table$grobs, function(x) x$name) == "guide-box")
## this is the tricky part !
## add a row in the second position (pos=2)
p_table$grobs[[leg]]$grobs[[1]] <-
gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]],
unit(0.5, "line"), ## you can increase the height here
pos=2) ## since I have 2 rows , I insert it in the middle
plot(p_table)


PS: I dont' know here how to coerce the table to a plot again! maybe someone else can help here ( I am just plotting it and losing the object structure)



enter image description here






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%2f32275113%2fggplot2-increase-space-between-legend-keys%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    51














    An alternative (and probably easier) solution is using legend.key and legend.key.size in the theme part of your code:



    ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
    geom_point() +
    guides(color = guide_legend(nrow = 2)) +
    theme(legend.direction = 'horizontal',
    legend.position = 'bottom',
    legend.key = element_rect(size = 5),
    legend.key.size = unit(1.5, 'lines'))


    this gives:



    enter image description here





    In case you are calling theme_bw or theme_classic before manipulating the legend, you should set the color of the legend rectangle:



    legend.key = element_rect(size = 5, color = 'white') #or: color = NA





    share|improve this answer


























    • Could you explain the difference between the size property of legend.key and the lines property of legend.key.size. Which one controls the spacing between the keys (i.e., the grey boxes + the label)?

      – Berk U.
      Jun 2 '16 at 21:20











    • @BerkU. The size parameter of legend.key determines the size of the boundary line. The lines property of legend.key.size determines the size of the whole box.

      – Jaap
      Jun 19 '16 at 16:34











    • This did not solve my situation, because the lines made some legend symbols increase together with the box. In my situation, the point symbol did not increase (same as your example) but the line symbol did. As my lines were vertical, the box kept getting taller as lines was increased, without increasing the space between the two columns of the legend. Will report back if I find a solution.

      – PatrickT
      Sep 30 '17 at 12:46






    • 1





      @PatrickT Not sure what your problem is. Maybe post as a new question?

      – Jaap
      Sep 30 '17 at 16:59











    • @Jaap, The problem came to bite me again and I couldn't remember if I had resolved it last time around (see my comment on 30 Sep 2017), so I posted a question: stackoverflow.com/questions/49668265/…

      – PatrickT
      Apr 5 '18 at 9:04
















    51














    An alternative (and probably easier) solution is using legend.key and legend.key.size in the theme part of your code:



    ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
    geom_point() +
    guides(color = guide_legend(nrow = 2)) +
    theme(legend.direction = 'horizontal',
    legend.position = 'bottom',
    legend.key = element_rect(size = 5),
    legend.key.size = unit(1.5, 'lines'))


    this gives:



    enter image description here





    In case you are calling theme_bw or theme_classic before manipulating the legend, you should set the color of the legend rectangle:



    legend.key = element_rect(size = 5, color = 'white') #or: color = NA





    share|improve this answer


























    • Could you explain the difference between the size property of legend.key and the lines property of legend.key.size. Which one controls the spacing between the keys (i.e., the grey boxes + the label)?

      – Berk U.
      Jun 2 '16 at 21:20











    • @BerkU. The size parameter of legend.key determines the size of the boundary line. The lines property of legend.key.size determines the size of the whole box.

      – Jaap
      Jun 19 '16 at 16:34











    • This did not solve my situation, because the lines made some legend symbols increase together with the box. In my situation, the point symbol did not increase (same as your example) but the line symbol did. As my lines were vertical, the box kept getting taller as lines was increased, without increasing the space between the two columns of the legend. Will report back if I find a solution.

      – PatrickT
      Sep 30 '17 at 12:46






    • 1





      @PatrickT Not sure what your problem is. Maybe post as a new question?

      – Jaap
      Sep 30 '17 at 16:59











    • @Jaap, The problem came to bite me again and I couldn't remember if I had resolved it last time around (see my comment on 30 Sep 2017), so I posted a question: stackoverflow.com/questions/49668265/…

      – PatrickT
      Apr 5 '18 at 9:04














    51












    51








    51







    An alternative (and probably easier) solution is using legend.key and legend.key.size in the theme part of your code:



    ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
    geom_point() +
    guides(color = guide_legend(nrow = 2)) +
    theme(legend.direction = 'horizontal',
    legend.position = 'bottom',
    legend.key = element_rect(size = 5),
    legend.key.size = unit(1.5, 'lines'))


    this gives:



    enter image description here





    In case you are calling theme_bw or theme_classic before manipulating the legend, you should set the color of the legend rectangle:



    legend.key = element_rect(size = 5, color = 'white') #or: color = NA





    share|improve this answer















    An alternative (and probably easier) solution is using legend.key and legend.key.size in the theme part of your code:



    ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
    geom_point() +
    guides(color = guide_legend(nrow = 2)) +
    theme(legend.direction = 'horizontal',
    legend.position = 'bottom',
    legend.key = element_rect(size = 5),
    legend.key.size = unit(1.5, 'lines'))


    this gives:



    enter image description here





    In case you are calling theme_bw or theme_classic before manipulating the legend, you should set the color of the legend rectangle:



    legend.key = element_rect(size = 5, color = 'white') #or: color = NA






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jun 19 '16 at 20:51

























    answered Aug 28 '15 at 17:52









    JaapJaap

    55.6k20119132




    55.6k20119132













    • Could you explain the difference between the size property of legend.key and the lines property of legend.key.size. Which one controls the spacing between the keys (i.e., the grey boxes + the label)?

      – Berk U.
      Jun 2 '16 at 21:20











    • @BerkU. The size parameter of legend.key determines the size of the boundary line. The lines property of legend.key.size determines the size of the whole box.

      – Jaap
      Jun 19 '16 at 16:34











    • This did not solve my situation, because the lines made some legend symbols increase together with the box. In my situation, the point symbol did not increase (same as your example) but the line symbol did. As my lines were vertical, the box kept getting taller as lines was increased, without increasing the space between the two columns of the legend. Will report back if I find a solution.

      – PatrickT
      Sep 30 '17 at 12:46






    • 1





      @PatrickT Not sure what your problem is. Maybe post as a new question?

      – Jaap
      Sep 30 '17 at 16:59











    • @Jaap, The problem came to bite me again and I couldn't remember if I had resolved it last time around (see my comment on 30 Sep 2017), so I posted a question: stackoverflow.com/questions/49668265/…

      – PatrickT
      Apr 5 '18 at 9:04



















    • Could you explain the difference between the size property of legend.key and the lines property of legend.key.size. Which one controls the spacing between the keys (i.e., the grey boxes + the label)?

      – Berk U.
      Jun 2 '16 at 21:20











    • @BerkU. The size parameter of legend.key determines the size of the boundary line. The lines property of legend.key.size determines the size of the whole box.

      – Jaap
      Jun 19 '16 at 16:34











    • This did not solve my situation, because the lines made some legend symbols increase together with the box. In my situation, the point symbol did not increase (same as your example) but the line symbol did. As my lines were vertical, the box kept getting taller as lines was increased, without increasing the space between the two columns of the legend. Will report back if I find a solution.

      – PatrickT
      Sep 30 '17 at 12:46






    • 1





      @PatrickT Not sure what your problem is. Maybe post as a new question?

      – Jaap
      Sep 30 '17 at 16:59











    • @Jaap, The problem came to bite me again and I couldn't remember if I had resolved it last time around (see my comment on 30 Sep 2017), so I posted a question: stackoverflow.com/questions/49668265/…

      – PatrickT
      Apr 5 '18 at 9:04

















    Could you explain the difference between the size property of legend.key and the lines property of legend.key.size. Which one controls the spacing between the keys (i.e., the grey boxes + the label)?

    – Berk U.
    Jun 2 '16 at 21:20





    Could you explain the difference between the size property of legend.key and the lines property of legend.key.size. Which one controls the spacing between the keys (i.e., the grey boxes + the label)?

    – Berk U.
    Jun 2 '16 at 21:20













    @BerkU. The size parameter of legend.key determines the size of the boundary line. The lines property of legend.key.size determines the size of the whole box.

    – Jaap
    Jun 19 '16 at 16:34





    @BerkU. The size parameter of legend.key determines the size of the boundary line. The lines property of legend.key.size determines the size of the whole box.

    – Jaap
    Jun 19 '16 at 16:34













    This did not solve my situation, because the lines made some legend symbols increase together with the box. In my situation, the point symbol did not increase (same as your example) but the line symbol did. As my lines were vertical, the box kept getting taller as lines was increased, without increasing the space between the two columns of the legend. Will report back if I find a solution.

    – PatrickT
    Sep 30 '17 at 12:46





    This did not solve my situation, because the lines made some legend symbols increase together with the box. In my situation, the point symbol did not increase (same as your example) but the line symbol did. As my lines were vertical, the box kept getting taller as lines was increased, without increasing the space between the two columns of the legend. Will report back if I find a solution.

    – PatrickT
    Sep 30 '17 at 12:46




    1




    1





    @PatrickT Not sure what your problem is. Maybe post as a new question?

    – Jaap
    Sep 30 '17 at 16:59





    @PatrickT Not sure what your problem is. Maybe post as a new question?

    – Jaap
    Sep 30 '17 at 16:59













    @Jaap, The problem came to bite me again and I couldn't remember if I had resolved it last time around (see my comment on 30 Sep 2017), so I posted a question: stackoverflow.com/questions/49668265/…

    – PatrickT
    Apr 5 '18 at 9:04





    @Jaap, The problem came to bite me again and I couldn't remember if I had resolved it last time around (see my comment on 30 Sep 2017), so I posted a question: stackoverflow.com/questions/49668265/…

    – PatrickT
    Apr 5 '18 at 9:04













    8














    Here a solution using gtable. Basically I am extracting legend grobs table and I add a row in the legend table.



    library(gtable)
    library(grid)
    ## transform the ggplot to a grobs table
    p_table <- ggplot_gtable(ggplot_build(p))
    ## extract legend
    leg <- which(sapply(p_table$grobs, function(x) x$name) == "guide-box")
    ## this is the tricky part !
    ## add a row in the second position (pos=2)
    p_table$grobs[[leg]]$grobs[[1]] <-
    gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]],
    unit(0.5, "line"), ## you can increase the height here
    pos=2) ## since I have 2 rows , I insert it in the middle
    plot(p_table)


    PS: I dont' know here how to coerce the table to a plot again! maybe someone else can help here ( I am just plotting it and losing the object structure)



    enter image description here






    share|improve this answer






























      8














      Here a solution using gtable. Basically I am extracting legend grobs table and I add a row in the legend table.



      library(gtable)
      library(grid)
      ## transform the ggplot to a grobs table
      p_table <- ggplot_gtable(ggplot_build(p))
      ## extract legend
      leg <- which(sapply(p_table$grobs, function(x) x$name) == "guide-box")
      ## this is the tricky part !
      ## add a row in the second position (pos=2)
      p_table$grobs[[leg]]$grobs[[1]] <-
      gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]],
      unit(0.5, "line"), ## you can increase the height here
      pos=2) ## since I have 2 rows , I insert it in the middle
      plot(p_table)


      PS: I dont' know here how to coerce the table to a plot again! maybe someone else can help here ( I am just plotting it and losing the object structure)



      enter image description here






      share|improve this answer




























        8












        8








        8







        Here a solution using gtable. Basically I am extracting legend grobs table and I add a row in the legend table.



        library(gtable)
        library(grid)
        ## transform the ggplot to a grobs table
        p_table <- ggplot_gtable(ggplot_build(p))
        ## extract legend
        leg <- which(sapply(p_table$grobs, function(x) x$name) == "guide-box")
        ## this is the tricky part !
        ## add a row in the second position (pos=2)
        p_table$grobs[[leg]]$grobs[[1]] <-
        gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]],
        unit(0.5, "line"), ## you can increase the height here
        pos=2) ## since I have 2 rows , I insert it in the middle
        plot(p_table)


        PS: I dont' know here how to coerce the table to a plot again! maybe someone else can help here ( I am just plotting it and losing the object structure)



        enter image description here






        share|improve this answer















        Here a solution using gtable. Basically I am extracting legend grobs table and I add a row in the legend table.



        library(gtable)
        library(grid)
        ## transform the ggplot to a grobs table
        p_table <- ggplot_gtable(ggplot_build(p))
        ## extract legend
        leg <- which(sapply(p_table$grobs, function(x) x$name) == "guide-box")
        ## this is the tricky part !
        ## add a row in the second position (pos=2)
        p_table$grobs[[leg]]$grobs[[1]] <-
        gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]],
        unit(0.5, "line"), ## you can increase the height here
        pos=2) ## since I have 2 rows , I insert it in the middle
        plot(p_table)


        PS: I dont' know here how to coerce the table to a plot again! maybe someone else can help here ( I am just plotting it and losing the object structure)



        enter image description here







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Aug 28 '15 at 18:12









        user20650

        17k43367




        17k43367










        answered Aug 28 '15 at 17:23









        agstudyagstudy

        98.6k11144203




        98.6k11144203






























            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%2f32275113%2fggplot2-increase-space-between-legend-keys%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

            Costa Masnaga

            Fotorealismo

            Sidney Franklin