在 ggplot 中仅向下移动一些 x 轴标签
Move only some x axis labels down in ggplot
看这个情节:
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = c(seq(0,10,2)/10, seq(2,10,1)))
轴开头的标签非常拥挤。有没有办法只下推 一些 标签(例如 c(0.2, 0.6, 0.8)
的标签)以便所有标签都可读?奖励:从刻度线到那些被向下推的标签添加一条垂直线(换句话说,使刻度线更长)。
我知道我可以像在 + theme(axis.text.x = element_text(vjust = -5))
中那样使用 vjust = -5
但这会压低所有标签。
这是一个非常简单的方法,通过在向量 x_ticks
.
中的标签前添加一个换行符 \n
来下推轴文本
library(tidyverse)
x_ticks <- c(seq(0,10,2)/10, seq(2,10,1))
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = x_ticks,
labels = ifelse(x_ticks %in% c(0.2, 0.6, 0.8),
paste0("\n", x_ticks), x_ticks))
由 reprex package (v2.0.1)
于 2022-03-30 创建
这是困难的方法,如果你真的想要那些长滴答声
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_vline(xintercept = seq(2, 10, 4)/10, color = "white", size = 0.5) +
geom_point() +
scale_x_continuous(breaks = c(seq(0,10,4)/10, seq(2,10,1))) +
coord_cartesian(clip = "off", ylim = c(-2, 2)) +
annotate("text", label = format(seq(2, 10, 4)/10, nsmall = 1),
x = seq(2, 10, 4)/10, y = -2.4,
size = 3) +
annotate("segment", x = seq(2, 10, 4)/10, xend = seq(2, 10, 4)/10,
y = -2.33, yend = -2.2, size = 0.2) +
theme(axis.text = element_text(color = "black"))
看这个情节:
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = c(seq(0,10,2)/10, seq(2,10,1)))
轴开头的标签非常拥挤。有没有办法只下推 一些 标签(例如 c(0.2, 0.6, 0.8)
的标签)以便所有标签都可读?奖励:从刻度线到那些被向下推的标签添加一条垂直线(换句话说,使刻度线更长)。
我知道我可以像在 + theme(axis.text.x = element_text(vjust = -5))
中那样使用 vjust = -5
但这会压低所有标签。
这是一个非常简单的方法,通过在向量 x_ticks
.
\n
来下推轴文本
library(tidyverse)
x_ticks <- c(seq(0,10,2)/10, seq(2,10,1))
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = x_ticks,
labels = ifelse(x_ticks %in% c(0.2, 0.6, 0.8),
paste0("\n", x_ticks), x_ticks))
由 reprex package (v2.0.1)
于 2022-03-30 创建这是困难的方法,如果你真的想要那些长滴答声
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_vline(xintercept = seq(2, 10, 4)/10, color = "white", size = 0.5) +
geom_point() +
scale_x_continuous(breaks = c(seq(0,10,4)/10, seq(2,10,1))) +
coord_cartesian(clip = "off", ylim = c(-2, 2)) +
annotate("text", label = format(seq(2, 10, 4)/10, nsmall = 1),
x = seq(2, 10, 4)/10, y = -2.4,
size = 3) +
annotate("segment", x = seq(2, 10, 4)/10, xend = seq(2, 10, 4)/10,
y = -2.33, yend = -2.2, size = 0.2) +
theme(axis.text = element_text(color = "black"))