鉴于以下情节:
library(tidyverse)
p <- ggplot(mtcars, aes(drat, disp)) +
geom_line()
p
layer_scales
可用于(此处)从大多数 ggplot
对象(如上面的对象)中提取中断/中断位置,例如
# layer_scales(p)$y$get_breaks()
as.numeric(na.omit(layer_scales(p)$y$break_positions()))
# [1] 100 200 300 400
# returns exactly the breaks that are in the plot
但是当我尝试从该图中提取这些内容时,它不起作用
df <- structure(list(date = structure(c(18080, 19281, 19096, 17178,
17692, 18659, 17129, 17114, 18833, 16472), class = "Date"), yy = c(1589L,
5382L, 4504L, 595L, 1027L, 2864L, 556L, 549L, 3346L, 42L)), class = "data.frame", row.names = c(NA,
-10L))
df
p1 <- ggplot(df, aes(x = date, y = yy)) +
geom_point()
p1
layer_scales(p1)$y$get_breaks()
# [1] 0 1000 2000 3000 4000 5000
as.numeric(na.omit(layer_scales(p1)$y$break_positions()))
# [1] 1000 2000 3000 4000 5000
# it doesn't return 0 2000 4000
知道为什么
layer_scales
在这种情况下不起作用吗?
我不太确定为什么
layer_scale()
不适用于p1
,但ggplot_build(p)$layout$panel_params[[1]]$y$get_breaks()
适用于两个图:
``` r
library(ggplot2)
df <- structure(list(date = structure(c(18080, 19281, 19096, 17178, 17692,
18659, 17129, 17114, 18833, 16472),
class = "Date"),
yy = c(1589L, 5382L, 4504L, 595L, 1027L,
2864L, 556L, 549L, 3346L, 42L)),
class = "data.frame", row.names = c(NA, -10L))
p <- ggplot(mtcars, aes(drat, disp)) +
geom_line()
p1 <- ggplot(df, aes(x = date, y = yy)) +
geom_point()
as.numeric(na.omit(ggplot_build(p)$layout$panel_params[[1]]$y$get_breaks()))
#> [1] 100 200 300 400
as.numeric(na.omit(ggplot_build(p1)$layout$panel_params[[1]]$y$get_breaks()))
#> [1] 0 2000 4000
创建于 2024 年 10 月 24 日,使用 reprex v2.0.2