Space between gpplot2 horizontal legend elements

前端 未结 6 1100
一生所求
一生所求 2020-12-17 18:17

I have a ggplot2 plot as follows:

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), fill=factor(cyl))) + 
    geom_bar() +
    coord_flip() +
    theme(legen         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 18:53

    This is another hack but one that I prefer, as it adds additional white space at the end of each label according to its number of characters. Replace fill = factor(cyl) with

    fill = sprintf("%-20s", factor(cyl)).

    This pads all strings in the vector with white characters on the right to reach 20 characters total. This is perfect if you have text labels of different lengths. You can change 20 to whatever number you want, or remove the negative sign to add spaces to the left instead of the right. In general sprintf() is a good function to explore and use for formatting text and numbers as desired.

提交回复
热议问题