【发布时间】:2019-07-27 08:09:10
【问题描述】:
(预先备注:我很高兴更改和编辑这篇文章,因为我知道这有多么重要,所以如果应该更改某些内容以使这篇文章更好,请原谅并批评我。)
我只想用 ggplot2::annotate() 绘制文本。文本字符串有特殊字符('\n'、'\t')。
我要绘制的字符串:
txttest <- "MSSubClass: Identifies the type of dwelling involved in the sale\n\n 20\t1-STORY 1946 & NEWER ALL STYLES\n 30\t1-STORY 1945 & OLDER\n 40\t1-STORY W/FINISHED ATTIC ALL AGES\n 45\t1-1/2 STORY - UNFINISHED ALL AGES\n 50\t1-1/2 STORY FINISHED ALL AGES\n 60\t2-STORY 1946 & NEWER\n 70\t2-STORY 1945 & OLDER\n 75\t2-1/2 STORY ALL AGES\n 80\tSPLIT OR MULTI-LEVEL\n 85\tSPLIT FOYER\n 90\tDUPLEX - ALL STYLES AND AGES\n 120\t1-STORY PUD (Planned Unit Development) - 1946 & NEWER\n 150\t1-1/2 STORY PUD - ALL AGES\n 160\t2-STORY PUD - 1946 & NEWER\n 180\tPUD - MULTILEVEL - INCL SPLIT LEV/FOYER\n 190\t2 FAMILY CONVERSION - ALL STYLES AND AGES\n\n"
当使用cat() 绘制它时,我得到以下信息:
MSSubClass: Identifies the type of dwelling involved in the sale 20 1-STORY 1946 & NEWER ALL STYLES 30 1-STORY 1945 & OLDER 40 1-STORY W/FINISHED ATTIC ALL AGES 45 1-1/2 STORY - UNFINISHED ALL AGES 50 1-1/2 STORY FINISHED ALL AGES 60 2-STORY 1946 & NEWER 70 2-STORY 1945 & OLDER 75 2-1/2 STORY ALL AGES 80 SPLIT OR MULTI-LEVEL 85 SPLIT FOYER 90 DUPLEX - ALL STYLES AND AGES 120 1-STORY PUD (Planned Unit Development) - 1946 & NEWER 150 1-1/2 STORY PUD - ALL AGES 160 2-STORY PUD - 1946 & NEWER 180 PUD - MULTILEVEL - INCL SPLIT LEV/FOYER 190 2 FAMILY CONVERSION - ALL STYLES AND AGES
(备注:MSSubClass:.. 缩进 4 个空格。在真正的 R 中,'MSSubClass:...' 比文本的其余部分更靠左。)
当使用ggplot2::annotate() 时,我需要将base::paste() 用于label 而不是base::cat()。不知道究竟是为什么。我认为是因为 cat() 和 paste() 不会创建相同类型的输出。
因此我得到以下代码:
ggplot() + annotate("text",x = 3,y = 25,size = 3,
label = paste(txttest)) +
theme_bw() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank()
)
此代码生成以下plot。
我尝试使用hjust = 0 使文本向左对齐:
ggplot() + annotate("text",x = 3,y = 25,size = 3,
label = paste(txttest), hjust = 0) +
theme_bw() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank()
)
创建this。 这具有正确的格式但奇怪的“间距”。并且调整 hjust 的值并不能解决问题。
如何绘制格式正确(类似于base::cat() 的输出)和居中(与hjust = 0 的选项相反)的文本? p>
【问题讨论】: