简体   繁体   English

如何通过在 ggplot2 中设置“theme(legend.title = element_blank())”去除多余的空间

[英]How to remove extra space left by setting "theme(legend.title = element_blank())“ in ggplot2

there!那里!

I want to remove legend title in ggplot2.我想删除 ggplot2 中的图例标题。 I used legend.title = element_blank(), but there is still some extra space at the top of the legend box where the legend title originally was.我使用了legend.title = element_blank(),但在图例框的顶部仍然有一些额外的空间,图例标题原来是这样的。 Actually, I don't want that space.其实,我不想要那个空间。 Anyone has ideas how to solve it?任何人都知道如何解决它? Thanks!谢谢!

Here is the code to replicate the unwanted extra space:这是复制不需要的额外空间的代码:

library(ggplot2)
library(grid)
df1 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)

# A basic graph
lp <- ggplot(data=df1, aes(x=time, y=total_bill, group=sex, shape=sex)) + geom_line() + geom_point()

lp + theme(legend.title=element_blank(),
           legend.background = element_rect(colour = "black", size = 0.1),
           legend.key.size = unit(0.4, "lines"))

the code snippet is taken from http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/ with a little modification.代码片段取自http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/稍作修改。 The extra space exists between the first legend key and the top border of the legend box.第一个图例键和图例框的顶部边框之间存在额外的空间。 I think it's because I resize the key size.我认为这是因为我调整了密钥大小。 When I remove `legend.key.size = unit(0.4, "lines"), everything is fine.当我删除 `legend.key.size = unit(0.4, "lines") 时,一切都很好。 However, I want to keep that line in my specific figure.但是,我想在我的具体数字中保留那条线。 I'm not sure if there is any way to solve that problem.我不确定是否有任何方法可以解决该问题。

This is my first answer ever.这是我有史以来的第一个答案。 theme(legend.margin=margin(t=-0.25,l=0.05,b=0.0,r=0.05, unit='cm')) The negative moves the space inwards. theme(legend.margin=margin(t=-0.25,l=0.05,b=0.0,r=0.05, unit='cm')) 负数将空间向内移动。

how about怎么样

p + theme(legend.position="none")

where p is the ggplot.其中p是 ggplot。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM