(预先说明:我很乐意更改和编辑此帖子,因为我知道这很重要,因此,请原谅并批评我是否应该进行一些更改以使此帖子变得更好。)
我只想用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。 格式正确,但奇怪的是“间距”。调整 just 的值不能解决问题。
如何绘制格式正确的文本(类似于base::cat()
的输出)和居中的(与带有hjust = 0
的选项相反) )?
答案 0 :(得分:0)
我找到了答案,并认为如果其他人可能想要做同样的事情,我会离开这篇文章。
只需添加hjust = 0, xmax = 4
,即可将文本向左对齐,并在右侧设置文本限制。