R: ggplot2让geom_text的字符完全覆盖一个X单位

3

我希望能根据字符串中的位置突出显示文本,例如如果我们有以下文本:

this is a really nice informative piece of text

我想说让我们在位置2到4周围画一个矩形:
t[his] is a really nice informative piece of text

我尝试在ggplot2中使用以下代码进行操作:
library(ggplot2)
library(dplyr)

box.data <- data.frame(
  start   = c(4,6,5,7,10,7),
  type    = c('BOX1.start', 'BOX1.start', 'BOX1.start','BOX1.end', 'BOX1.end', 'BOX1.end'),
  text.id = c(1,2,3,1,2,3)
)

text.data <- data.frame(
  x = rep(1,3),
  text.id = c(1,2,3),
  text = c('Thisissomerandomrandomrandomrandomtext1',
           'Thisissomerandomrandomrandomrandomtext2',
           'Thisissomerandomrandomrandomrandomtext3')
)


ggplot(data = text.data, aes(x = x, y = text.id)) + 
  scale_x_continuous(limits = c(1, nchar(as.character(text.data$text[1])))) +
  geom_text(label = text.data$text, hjust = 0, size = 3) +
  geom_line(data = box.data, aes(x = start, y = text.id, group = text.id, size = 3, alpha = 0.5, colour = 'red'))

这会生成以下图表:
enter image description here 我的方法失败了,因为一个字母不能刚好覆盖x轴上的一个单位,有什么方法可以解决这个问题吗?
1个回答

1
我刚刚发现,我可以将字符串拆分成字符并绘制这些字符,也许对其他人有用。
library(ggplot2)
library(dplyr)
library(splitstackshape)

# First remember the plotting window, which equals the text length
text.size = nchar(as.character(text.data$text[1]))

# Split the string into single characters, and adjust the X-position to the string position
text.data <- cSplit(text.data, 'text', sep = '', direction = 'long', stripWhite = FALSE) %>%
  group_by(text.id) %>%
  mutate(x1 = seq(1,n()))

# Plot each character and add highlights 
ggplot(data = text.data, aes(x = x1, y = text.id)) + 
  scale_x_continuous(limits = c(1, text.size)) +
  geom_text(aes(x = text.data$x1, y = text.data$text.id,  group = text.id, label = text)) +
  geom_line(data = box.data, aes(x = start, y = text.id, group = text.id, size = 3, alpha = 0.5, colour = 'red'))

这将生成以下图表:
输入图像描述

也许标记应该向上下方稍微延伸一点,但这很容易解决。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接