R: ggplot2 позволяет символам geom_text точно покрывать одну единицу X - PullRequest
0 голосов
/ 23 октября 2018

Я хочу выделить текст на основе позиции в строке, например, если у нас есть этот текст:

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 голосов
/ 23 октября 2018

Я только что понял, что могу разбить строку на символы и построить их, возможно, это будет полезно для кого-то еще.

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

Возможно, маркировка должна немного расширяться, но вверх и вниз, но это легко исправить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...