我有一个ggplot2图如下:
library(ggplot2)
ggplot(mtcars, aes(factor(cyl), fill=factor(cyl))) +
geom_bar() +
coord_flip() +
theme(legend.position = 'top') +
guides(fill = guide_legend(title=NULL))
Run Code Online (Sandbox Code Playgroud)
我想在填充元素之间添加间距,如下所示:
alistaire 和 Tyler Rinker 提到的问题就解决了。现在我们可以调整 element_text` 的边距。
ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) +
geom_bar() +
coord_flip() +
theme(
legend.position = 'top',
legend.title = element_blank(),
legend.text = element_text(margin = margin(r = 2, unit = 'cm'))
)
Run Code Online (Sandbox Code Playgroud)
看起来似乎确实是theme(legend.text = element_text(margin = margin(r = 2, unit = 'in')))完成任务的正确方法,但这根本无济于事。
相反,(并且不是第一次)我回到了Microsoft Word风格的对齐攻击,即仅添加空格:
ggplot(mtcars, aes(factor(cyl), fill=factor(paste(cyl, ' ')))) +
geom_bar() +
coord_flip() +
theme(legend.position = 'top') +
guides(fill = guide_legend(title=NULL))
Run Code Online (Sandbox Code Playgroud)
因为上面也有空格8,所以它有点偏离中心,但是如果您将它们粘贴到以前的标签上,则可以根据需要微调它们。
对于造成平面设计师的噩梦,我们深表歉意。