从 ggplot2 对象中提取使用过的比例
Extract used scales from ggplot2 object
我想写一个 ggplot2 主题,当 x 轴包含数值或因子时,它以不同的方式格式化 x 轴。
是否可以从主题调用中检测到使用了哪种类型的比例?如果是,如何?
我的代码看起来像这样,我正在寻找一个表达式来替换尖括号中的伪代码:
my_theme <- function(){
thm <- theme_bw() %+replace%
theme(
panel.border = element_blank()
)
if(<x-Axis scale is factor?>){
thm <- thm %+replace%
axis.ticks.x = element_blank()
}
thm
}
layer_scales
是 ggplot2 中的一个辅助函数,它 returns 与绘图的图层(默认情况下是第一个 geom 图层)相关联的比例,所以像 class(layer_scales(plot)$x)
这样的东西可以告诉你是你正在处理的 x 轴类型。
这是一个如何实施的示例:
# continuous x-axis plot (the additional specifications are there to make sure
# its look closely matches the next one
p1 <- ggplot(mtcars, aes(gear, wt, colour = factor(cyl))) +
geom_point(size = 4, show.legend = FALSE) +
scale_x_continuous(breaks = c(3, 4, 5),
expand = c(0, 0.6))
# discrete x-axis plot
p2 <- ggplot(mtcars, aes(factor(gear), wt, colour = factor(cyl))) +
geom_point(size = 4, show.legend = FALSE)
my_theme <- function(plot){
thm <- theme_bw() %+replace%
theme(
panel.border = element_blank()
)
if("ScaleDiscrete" %in% class(layer_scales(plot)$x)){
thm <- thm %+replace%
theme(
axis.ticks.x = element_blank()
)
}
plot + thm
}
# check the difference in results for p1 & p2. p1 has axis ticks while p2 does not.
gridExtra::grid.arrange(my_theme(p1), my_theme(p2), nrow = 1)
我想写一个 ggplot2 主题,当 x 轴包含数值或因子时,它以不同的方式格式化 x 轴。
是否可以从主题调用中检测到使用了哪种类型的比例?如果是,如何?
我的代码看起来像这样,我正在寻找一个表达式来替换尖括号中的伪代码:
my_theme <- function(){
thm <- theme_bw() %+replace%
theme(
panel.border = element_blank()
)
if(<x-Axis scale is factor?>){
thm <- thm %+replace%
axis.ticks.x = element_blank()
}
thm
}
layer_scales
是 ggplot2 中的一个辅助函数,它 returns 与绘图的图层(默认情况下是第一个 geom 图层)相关联的比例,所以像 class(layer_scales(plot)$x)
这样的东西可以告诉你是你正在处理的 x 轴类型。
这是一个如何实施的示例:
# continuous x-axis plot (the additional specifications are there to make sure
# its look closely matches the next one
p1 <- ggplot(mtcars, aes(gear, wt, colour = factor(cyl))) +
geom_point(size = 4, show.legend = FALSE) +
scale_x_continuous(breaks = c(3, 4, 5),
expand = c(0, 0.6))
# discrete x-axis plot
p2 <- ggplot(mtcars, aes(factor(gear), wt, colour = factor(cyl))) +
geom_point(size = 4, show.legend = FALSE)
my_theme <- function(plot){
thm <- theme_bw() %+replace%
theme(
panel.border = element_blank()
)
if("ScaleDiscrete" %in% class(layer_scales(plot)$x)){
thm <- thm %+replace%
theme(
axis.ticks.x = element_blank()
)
}
plot + thm
}
# check the difference in results for p1 & p2. p1 has axis ticks while p2 does not.
gridExtra::grid.arrange(my_theme(p1), my_theme(p2), nrow = 1)