如何在ggplot2竖排文本列中增大文本行间距?
解决ggplot竖排文本行间距过小的问题
你设置的lineheight参数无效是因为它仅作用于单个文本标签内部的多行内容(比如标签包含\n换行符时),而你这里每个geom_text对应独立的单个数字,所以这个参数不会改变行与行之间的间距。
要增大竖排文本的行间距,核心是调整y轴上的刻度间距,以下是几种有效方法:
方法1:将离散y变量转为连续变量并缩放间距
把id转换为数值后,乘以一个大于1的系数来放大行间距,精准控制间距宽度:
p2 <- df |> mutate(x = "col1", # 将反转后的id转为数值,乘以系数(比如1.2)放大行间距,可按需调整系数 y_scaled = as.numeric(fct_rev(id)) * 1.2) |> ggplot(aes(x = x, y = y_scaled)) + geom_text(aes(label = 1:72), hjust = align, size = 3) + geom_stripped_rows() + theme(axis.text = element_blank(), axis.ticks = element_blank(), axis.title.y = element_blank(), panel.grid = element_blank(), panel.background = element_blank(), plot.margin = unit(rep(0,4),"cm") ) + labs(x = "cancer_type") + scale_x_discrete(position = "top") p2
方法2:调整y轴expand参数(快速增加整体空白)
如果只是想快速提升行间距的视觉效果,可以通过scale_y_discrete的expand参数增加轴两端的空白:
p2 <- df |> mutate(x="col1") |> ggplot(aes(x=x,y=fct_rev(id)))+ geom_text(aes(label=1:72),hjust=align,size=3)+ geom_stripped_rows()+ theme(axis.text = element_blank(), axis.ticks = element_blank(), axis.title.y = element_blank(), panel.grid = element_blank(), panel.background = element_blank(), plot.margin = unit(rep(0,4),"cm") )+ labs(x="cancer_type")+ scale_x_discrete(position = "top") + # 调整mult参数控制空白比例,数值越大空白越多 scale_y_discrete(expand = expansion(mult = c(0.1, 0.1))) p2
方法3:position_nudge微调单行文本题位
如果需要对个别文本位置做针对性调整,可使用position_nudge批量偏移:
p2 <- df |> mutate(x="col1") |> ggplot(aes(x=x,y=fct_rev(id)))+ geom_text(aes(label=1:72),hjust=align,size=3, # y值偏移量可按需调整,正数向上偏移 position = position_nudge(y = 0.5))+ geom_stripped_rows()+ theme(axis.text = element_blank(), axis.ticks = element_blank(), axis.title.y = element_blank(), panel.grid = element_blank(), panel.background = element_blank(), plot.margin = unit(rep(0,4),"cm") )+ labs(x="cancer_type")+ scale_x_discrete(position = "top") p2
内容的提问来源于stack exchange,提问作者wzy
相关产品推荐
相关产品推荐

