如何控制y轴上geom_text的间距/缩放?

时间:2017-11-06 22:28:28

标签: r ggplot2 geom-text

我不知道如何控制ggplot2中“行”之间文本的间距。例如,下面的函数绘制空网格上的文本行:

library(tidyverse)
plot_text <- function(rows) {
  tibble(text = sprintf("Line %s", 1:rows), 
         x = 1, 
         y = rev(1:rows)) %>% 
    ggplot(aes(x, y)) +
    geom_text(aes(label = text)) +
    theme_void() +
    ylim(-5, rows) #I want to leave some whitespace on the bottom
}

但是,每个“行”之间的间距根据行数而变化:

plot_text(rows = 5)
plot_text(rows = 10)
plot_text(rows = 20)

如何锁定或控制行之间的间距,以便文本总是相同,无论行数是多少?

1 个答案:

答案 0 :(得分:1)

我使用变量ylim进行的任何尝试都证明是不一致的,所以我决定修复ylim并遵循:

library(tidyverse)
plot_text <- function(rows) {
  if(rows < 1){
    stop ("try again")}
  if(rows == 1){
    g = 20
  } else { g = c(20,20-1*(1:(rows-1)))}
  tibble(text = sprintf("Line %s", 1:rows), 
         x = 1, 
         y = g) %>% 
    ggplot(aes(x, y = y)) +
    geom_text(aes(label = text)) +
    theme_void()+
    ylim(-5, 20) 
}
library(gridExtra)
do.call("grid.arrange", c(lapply(1:10, function(x) plot_text(x)), ncol = 5))

enter image description here