Reputation: 1084
I do not know how to control the spacing of the text between "rows" in ggplot2. For example, the function below plots rows of text on an empty grid:
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
}
However, the spacing between each "row" varies according to the number of rows:
plot_text(rows = 5)
plot_text(rows = 10)
plot_text(rows = 20)
How can I lock or control the spacing between rows, so that the text always scales the same, no matter the number of rows?
Upvotes: 0
Views: 597
Reputation: 19716
Any attempts that I have made with a variable ylim
proved to be inconsistent, so I decided to fix the ylim and conform to that:
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))
Upvotes: 1