在R的ggplot中使用marquee包时,如何控制标题换行与行间距?
ggplot中marquee包标题格式问题解答
1. 为什么单个\n无法换行,必须用两个?
marquee的element_marquee默认会把单个换行符\n当成空格处理,只有连续两个\n才会被识别为段落分隔,从而触发换行效果。这是因为它底层基于grid文本渲染系统,默认的文本解析逻辑会合并单个换行和普通空白字符。
2. 怎么控制标题行间距?
你之前用lineheight = relative(0.5)没生效,是因为这个参数管的是段落内部的行间距,但你用\n\n创建的是独立段落,段落之间的间距由margin参数控制。要缩小行间距,得调整两个关键点:
- 如果是段落内自动换行的文本,用
lineheight控制行高; - 如果是用
\n\n分隔的段落,要通过margin里的上下边距来缩小段落间隔。
修正后的代码可以这么写:
library(marquee) library(ggplot2) my_style <- modify_style( classic_style(), "my_style", lineheight = relative(0.8), # 控制同一段落内的行间距 margin = trbl(0, 0, 0, 0) # 移除段落间的上下边距 ) ggplot() + labs(title = "A good figure title is long because:\n it includes details on what was studied, when the data\n were collected, and where. For example, this is a bunch of data on fuel economy for cars\n gathered from a small planet which some call Earth between the years 1999 and 2008.") + theme(title = element_marquee(style = my_style, parse = FALSE)) # 关闭解析,避免特殊字符干扰
注意这里把原来的\n\n改成了单个\n,这样文本会被当成同一段落,lineheight就能生效控制行间距了。
3. marquee实现标题自动换行的简便方法
不用手动加\n,直接给element_marquee设置width参数限制标题宽度,文本就会自动换行:
ggplot() + labs(title = "A good figure title is long because: it includes details on what was studied, when the data were collected, and where. For example, this is a bunch of data on fuel economy for cars gathered from a small planet which some call Earth between the years 1999 and 2008.") + theme(title = element_marquee(style = my_style, width = unit(0.8, "npc"))) # 宽度设为绘图区域的80%
这里width = unit(0.8, "npc")表示标题宽度占绘图区域的80%,超出部分自动换行,再配合lineheight就能轻松调整行间距。
内容的提问来源于stack exchange,提问作者itsMeInMiami
相关产品推荐
相关产品推荐

