我一直试图在ggplot2中绘图。在x轴上,我有因素。在y轴上,我有非常小或非常大的值,当我在绘图时,在绘图的中间部分没有任何东西。我想要挤压这个中间部分,但希望y轴的顺序相反(100,90,80 ... 0)。我搜索并发现通过使用从Stackoverflow借来的函数来压缩中间部分。功能是:
squish_trans <- function(from, to, factor) {
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("squished", trans, inv))
}
此功能非常有效,但是,我想要反转y轴。无法做到这一点。请帮忙。 数据如下所示:
s<-
"Groups Mean Stdev
F 99 0.414048151
F 98 0.457120465
F 92 0
F 1 0.01
J 80 1.638558759
E 88 0.681379406
M 83 0.01
M 1 0.01"
S <- read.delim(textConnection(s),header=TRUE,sep=" ",strip.white=TRUE)
答案 0 :(得分:2)
如果你看一下:
> scale_y_reverse
function (...)
{
scale_y_continuous(..., trans = reverse_trans())
}
<environment: namespace:ggplot2>
> reverse_trans
function ()
{
trans_new("reverse", function(x) -x, function(x) -x, minor_breaks = regular_minor_breaks(reverse = TRUE))
}
您会发现只需使用-x进行转换及其反转
require(scales)
squish_trans <- function(from, to, factor) {
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("squish_and_reverse", trans, inv))
}
ggplot(S,aes(x=Groups,y=Mean))+geom_point()+
scale_y_continuous(trans = squish_trans(10, 80, 5))
答案 1 :(得分:0)
我建议只计算数据的分档,然后使用bin facet_grid()
。这是一个例子:
# example data
df <- data.frame(group=rep(c('A', 'B', 'C', 'D'), 10),
value=c(rnorm(10), rnorm(10)+100)
)
# compute bins (using tidyverse packages tidyr and dplyr)
df %>%
mutate(bin = value > 50) %>%
# plot the data using a facet_grid with free y scales
ggplot(aes(x=group, y=value)) +
facet_grid(bin ~ ., scale='free_y') +
geom_point() +
scale_y_reverse()
# save plot
ggsave('SO_47234710.png', width=4, height=3)
使用此方法时使用scale='free_y'
至关重要,以便方面具有单独的y刻度。