使用 \n 换行时,在 geom_label() 和 geom_text() 中减少 R ggplot 中的行高

问题描述

以下代码创建以下图表:

data.frame(x = c(1,2,3,4),y = c(1,4)) %>% 
  ggplot() + 
  geom_point(aes(x = x,y = y)) + 
  geom_label(aes(x = 2.5,y = 2.5,label = 'label here \n with break'),fill = '#dddddd')

enter image description here

我们需要减少两行文本之间的差距。我相信这与 css 正确对应 line-height,当行高较小时,减少会使线条更靠近。

我们无法使用不同的 y 值渲染 2 个 geom_labels,因为在调整图形大小时,垂直定位与 2 个 geom_labels 不一致。我们需要使用 1 geom_label() 和 \n 来换行,我们需要减少两行文本之间的差距。可以这样做吗?

解决方法

试试 lineheight 中的 geom_label 参数:

data.frame(x = c(1,2,3,4),y = c(1,4)) %>% 
  ggplot() + 
  geom_point(aes(x = x,y = y)) + 
  geom_label(aes(x = 2.5,y = 2.5,label = 'label here \n with break'),fill = '#dddddd',lineheight = 0.5) 

enter image description here