如何在 R ggplot 中改变 geom_text 中的文本长度?

How to vary the length of text in geom_text in R ggplot?

我正在使用 R 中的 ggplot 中的 geom_label 绘制一些文本,但我不知道如何根据变量改变文本的大小。请注意,"size" 不是指文本的宽度,而是指它的长度。考虑以下虚拟数据及其生成的图形:

x.cord <- c(4,5,1,6)
duration <- c(0.4, 0.7, 0.2, 0.3)
text <- c("know", "boy", "man", "gift")

df <- data.frame(cbind(x.cord, duration, text))


p <- ggplot(df, aes(x.cord, rownames(df), label = text))

p + geom_label(aes(fill=text))

在上面的图中,我可以绘制位于 x.cord 的文本(即 x 坐标),但我还希望文本的长度等于持续时间变量。

如果我使用尺寸参数如下:

p + geom_label(aes(fill=text, size=duration))

我得到下图:

我可以根据持续时间变量控制文本的 'width',如上图所示,但我似乎找不到任何可以帮助我控制 [=31] 的参数=] 的文本框。有什么建议吗?

这不是最优雅的解决方案,但我不能 100% 确定您想要什么。我认为这也是 EcologyTom 的想法。也许是这样的?

x.cord <- c(4,5,1,6)
duration <- c(0.4, 0.7, 0.2, 0.3)
text <- c("know", "boy", "man", "gift")
df <- data.frame(cbind(as.numeric(x.cord), as.numeric(duration), text))

p = ggplot(df, aes(x.cord, as.numeric(rownames(df)), label = text)) +
  geom_tile(aes(x = x.cord, y = as.numeric(rownames(df)), width = duration, height = 0.1, fill = text)) +
  geom_text()
p