【问题标题】:Increase Vertical Spacing between Legend Key in ggplot2增加ggplot2中图例键之间的垂直间距
【发布时间】:2021-02-22 15:31:36
【问题描述】:

如何增加图例键之间的垂直间距:

p1 <- ggplot(data = HSS, mapping = aes(x = EVENT, y = HSS, fill = TIME)) + 
            geom_bar(stat = "identity",width=0.7, colour = "black", position = position_dodge(0.7)) + 
            scale_fill_manual("HSS", values = c("deepskyblue3", "indianred2"), 
            labels = c("1200 UTC  (0.049)", "0000 UTC  (0.031)")) + theme_bw()

p1 <- p1 + scale_y_continuous(expand = expansion(mult = c(0.0085, -0.085)), 
           limits = c(-0.03,0.5), breaks = c(-0.03,-0.01, 0.01, 0.03, 0.05, 0.07,0.09,0.11,0.13,0.15,0.17,
                                             0.19, 0.21,0.23,0.25,0.27,0.29,0.31,0.33,0.45),
           
           labels = c("-0.03","-0.01","0.01","0.03","0.05","0.07","0.09","0.11","0.13","0.15","0.17",
                      "0.19","0.21","0.23","0.25","0.27","0.29","0.31","0.33","0.45")) + 
  
          theme(axis.text.x=element_text(color = "black", size=12, face = "bold", angle=90, vjust=.5,
                 hjust=0.8)) + 
          theme(axis.text.y = element_text(color = "black", size=12, face = "bold"))




p1 <- p1 + theme( axis.line = element_line(colour = "black", size = 0.5, linetype = "solid")) + 
                          labs( y = "HSS")


p1 <- p1 + theme(axis.title=element_text(colour = "blue2"  ,size=14,face="bold", vjust = 0.1))

p1 <-  p1 +  theme(legend.position=c(0.98,0.98)) + theme(legend.title=element_blank(), 
                                                         legend.text = element_text(face =  "bold", size = "12"), 
                                                         legend.box.background = element_rect(size=0.7, linetype="solid"),
                                                         legend.justification = c("right", "top"),
                                                         legend.box.margin = margin(1, 1, 1, 1) 
                                                         )
p1
                                          

我尝试使用 legend.key.height legend.spacing.y guide 但它只拉伸了图例键而没有在它们之间添加空格。另外,如何删除 Y 轴的备用标签(带圆圈)保持 tickmark 与绘图。

【问题讨论】:

  • 您是否将这张图片保存在某个地方?如果这是图像预览器的屏幕截图,那么它实际上可能不是问题
  • @TheSciGuy 这不是图像预览器的截图。这是上面脚本中的实际图像。
  • 我的意思是,您是通过ggsave() 或其他图像导出器(例如pdf())导出绘图吗?尝试使用ggsave(p1, height = 8, width = 12, units = "in", dpi = 300) 导出稍大的图像并上传该图像。因为您的示例不可重现(即我无法使用提供的代码重新创建您的绘图),这是最简单的选择。
  • @TheSciGuy 我正在使用pdfimage exporter 导出,但它不起作用。我也尝试了您的建议,但没有运气。

标签: r ggplot2 legend


【解决方案1】:

在浏览了 ggplot2 的源代码后,我得出的结论是 legend.spacing.y 仅在 byrow = TRUE 作为图例的参数时应用。

下面的简单示例。

library(ggplot2)

ggplot(iris, aes(Sepal.Width)) +
  geom_density(aes(fill = Species)) +
  guides(fill = guide_legend(byrow = TRUE)) +
  theme(legend.spacing.y = unit(1, "cm"))

关于标签,只需从scale_y_continuous() 中的breaks 参数中删除您不想显示的值,您已经手动指定了它们。

【讨论】:

  • 感谢第一部分...它可以增加图例键中的垂直间距。关于 Y 轴标签,我不想将它们从 breaks 中删除,因为它还会删除这两个中断之间的背景线。我想保留这些线(例如,中断 0.01 和 0.03 之间的背景比例线 0.02 )。