R:ggplot2让geom_text的字符精确地覆盖一个X单位

时间:2018-10-23 12:09:52

标签: r ggplot2 text

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

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 个答案:

答案 0 :(得分: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'))

产生以下情节的地方:
enter image description here

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