如何控制y轴上geom_text的spacing/scaling?
How do I control the spacing/scaling of geom_text on the y-axis?
我不知道如何控制ggplot2中"rows"之间的文本间距。例如,下面的函数在空网格上绘制文本行:
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
}
但是,每个 "row" 之间的间距根据行数而变化:
plot_text(rows = 5)
plot_text(rows = 10)
plot_text(rows = 20)
如何锁定或控制行间距,以便无论行数如何,文本始终缩放相同?
我对变量 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))
我不知道如何控制ggplot2中"rows"之间的文本间距。例如,下面的函数在空网格上绘制文本行:
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
}
但是,每个 "row" 之间的间距根据行数而变化:
plot_text(rows = 5)
plot_text(rows = 10)
plot_text(rows = 20)
如何锁定或控制行间距,以便无论行数如何,文本始终缩放相同?
我对变量 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))