gpt4 book ai didi

r - 如何删除部分 y 轴并反转 ggplot2 中的轴

转载 作者:行者123 更新时间:2023-12-04 02:01:01 25 4
gpt4 key购买 nike

我一直在尝试在 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)

最佳答案

如果你调查:

> 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))

enter image description here

关于r - 如何删除部分 y 轴并反转 ggplot2 中的轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com