我想跳过大部分-10到100之间的数据集的y轴部分,然后再跳过一些400的值。所以我想挤压这个空白区域。我已经在我的绘图中使用了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] <-from +(x [isq]-from)* factor错误:下标分配中不允许使用NA
我不明白,因为我的数据中没有NA,示例数据中也没有NA。
到底是怎么回事?
使用browser()
if找出问题是在inv
压缩转换的一部分中出现的。但是我只能猜测原因是什么,可能与中断的设置方式(??)有关。但是,scale_y_continuous
我没有通过内部应用转换,而是尝试通过coord_trans
... et voila应用了转换:
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))
由reprex软件包(v0.3.0)创建于2020-04-03
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句