如何使用ggplot沿x轴均匀对齐文本?

时间:2018-02-12 06:28:29

标签: r ggplot2 geom-text

我需要在ggplot中绘制大量缩放的整齐文本。难点在于缩放x坐标。我尝试了各种缩放功能(见下文),但我无法整齐地对齐文本。例如:

library(tidyverse)
library(stringr)

scaleX <- function(x) cumsum(map_dbl(x, nchar)) - map_dbl(x, nchar)

df <- tibble(
  sentences = c("This is a short sentence",
        "This is a longer sentences with more words",
        "A third sentence"),
  y = 3:1) %>% 
     mutate(words = str_split(sentences, " "),
            x = map(words, ~scaleX(.))) %>% 
     unnest() %>% 
     mutate(wordFill = ifelse(str_detect(words, "a|b|c|d|e"),  TRUE, FALSE))

ggplot(df, aes(x, y)) +
  geom_text(aes(label = words, color = wordFill))

如何缩放单词以使它们均匀对齐?

0 个答案:

没有答案