gpt4 book ai didi

R: ggplot2让geom_text的字符正好覆盖1个X单位

转载 作者:行者123 更新时间:2023-12-01 16:47:12 24 4
gpt4 key购买 nike

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

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 轴的一个单位,有什么办法可以实现这一点吗?

最佳答案

我刚刚发现我可以将字符串拆分为字符并绘制它们,也许对其他人有用。

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

也许标记应该向上和向下延伸一点,但这是一个简单的解决方法。

关于R: ggplot2让geom_text的字符正好覆盖1个X单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52948760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com