对于大多数值在-10和100之间,然后在400处又少一些的数据集,我想跳过我的y轴的一部分。所以我想挤压这个空白区域。我已经在我的绘图中使用了Facet网格用于3种不同的场景,因此,我宁愿仅“挤压” Y轴而不创建多个绘图。
我在RPubs(https://rpubs.com/huanfaChen/squash_remove_y_axix_ggplot_)上找到了“ squash_axis”功能,该功能可能会对我有所帮助。但是我无法使其与我自己的数据集一起使用,甚至无法与示例数据集一起使用。
示例数据集(除了带有时间的另一列之外,我的数据集看起来非常相似)
dat <- data.frame(group=rep(c('A', 'B', 'C', 'D'), each = 10),
value=c(rnorm(10), rnorm(10)+100)
)
然后是壁球轴功能:
require(ggplot2)
squash_axis <- function(from, to, factor) {
# A transformation function that squashes the range of [from, to] by factor on a given axis
# Args:
# from: left end of the axis
# to: right end of the axis
# factor: the compression factor of the range [from, to]
#
# Returns:
# A transformation called "squash_axis", which is capsulated by trans_new() function
trans <- function(x) {
# get indices for the relevant regions
isq <- x > from & x < to
ito <- x >= to
# apply transformation
x[isq] <- from + (x[isq] - from)/factor
x[ito] <- from + (to - from)/factor + (x[ito] - to)
return(x)
}
inv <- function(x) {
# get indices for the relevant regions
isq <- x > from & x < from + (to - from)/factor
ito <- x >= from + (to - from)/factor
# apply transformation
x[isq] <- from + (x[isq] - from) * factor
x[ito] <- to + (x[ito] - (from + (to - from)/factor))
return(x)
}
# return the transformation
return(trans_new("squash_axis", trans, inv))
}
以及示例中的情节:
ggplot(dat,aes(x=group,y=value))+
geom_point()+
scale_y_continuous(trans = squash_axis(5, 95, 10))
然后我得到了错误:x [isq]的误差
我不明白,因为我的数据中没有NA,示例数据中也没有NA。
发生了什么事?
如果发现问题出现在压缩转换的browser()
部分中,则使用inv
。但是我只能猜测原因是什么,可能与中断的设置方式(??)有关。但是,我没有通过scale_y_continuous
来应用转换,而是尝试通过coord_trans
来应用它,等等,工作:
library(ggplot2)
dat <- data.frame(group=rep(c('A', 'B', 'C', 'D'), each = 10),
value=c(rnorm(10), rnorm(10)+100)
)
squash_axis <- function(from, to, factor) {
# A transformation function that squashes the range of [from, to] by factor on a given axis
# Args:
# from: left end of the axis
# to: right end of the axis
# factor: the compression factor of the range [from, to]
#
# Returns:
# A transformation called "squash_axis", which is capsulated by trans_new() function
trans <- function(x) {
# get indices for the relevant regions
isq <- x > from & x < to
ito <- x >= to
# apply transformation
x[isq] <- from + (x[isq] - from)/factor
x[ito] <- from + (to - from)/factor + (x[ito] - to)
return(x)
}
inv <- function(x) {
# get indices for the relevant regions
isq <- x > from & x < from + (to - from)/factor
ito <- x >= from + (to - from)/factor
# apply transformation
x[isq] <- from + (x[isq] - from) * factor
x[ito] <- to + (x[ito] - (from + (to - from)/factor))
return(x)
}
# return the transformation
return(scales::trans_new("squash_axis", trans, inv, domain = c(from, to)))
}
ggplot(dat,aes(x=group, y = value))+
geom_point()+
coord_trans(y = squash_axis(5, 95, 10))
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9ZdHVmVkh2LnBuZyJ9” alt =“”>
由reprex package(v0.3.0)在2020-04-03创建