ggplot中的压缩轴 [英] Compressing axis in ggplot

查看:60
本文介绍了ggplot中的压缩轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情节

p1<-ggplot(data.frame(x=c(-10, 30),y=c(0,250)), aes(x,y))
p1<-p1 +stat_function(fun=function(x)12+180/(1+exp(-.759*(x-7.69))),size = 2,color="yellow")+coord_cartesian(ylim=c(0, 250))+geom_abline(intercept = 44, slope = 0,lty=2)+scale_x_continuous(limits=c(-5,25))+ geom_ribbon(aes(ymin=0, ymax=80))
print(p1)   

我正在尝试更改轴,以使虚线上方的部分被压缩",而虚线下方的部分则被扩展(但不更改轴).换句话说,我希望图的下部比例变大而上部的比例变窄,以使虚线下方的图部分更显眼.但是,我似乎无法弄清楚该如何做.有什么建议吗?

I am trying to change the axes so that the part above dotted line gets "squashed" and the part below dotted line) gets expanded (but without changing the axes). In other words, I want the scale of the lower part of the plot to be wider and the scale of the upper part to be narrower so that the part of the plot below the dotted line is more prominently displayed. However, I can't seem to figure out how to do this. Any suggestions?

谢谢.

推荐答案

我希望我已经正确理解了您的需求.

I hope I had understood correctly what you need.

我不知道@ 42-评论是什么,但我认为绝对可以采用协调转换.

I don't know what @42- comment was, but I think a coord transformation is definitely the way to go.

library(scales)
magnify_trans <- function(intercept, reducer) {

    trans <- function(x, i = intercept, r = reducer) {
        sapply(x, function(x) {
            if (x < i) x
            else x / r + i
        })
    }

    inv <- function(x, i = intercept, r = reducer) {
        sapply(x, function(x) {
            if(!is.na(x)) {
                if (x < i) x
                else (x - i) * r
            }
        })
    }

    trans_new(name = 'custom',
              transform = trans,
              inverse = inv
              )
}

我们定义了一个 transformation ,该转换将 intercept 以上的值除以 reducer arg.

We defined a transformation that divides the values above intercept by the reducer arg.

library(ggplot2)
ggplot(data.frame(x = c(-10, 30), y = c(0, 250)), aes(x, y)) +
    stat_function(fun = function(x) 12 + 180 / (1 + exp(-.759*(x - 7.69))),
                  size = 2,
                  color = "yellow") +
    coord_cartesian(ylim = c(0, 250))+
    geom_abline(intercept = 44, slope = 0, lty = 2)+
    scale_x_continuous(limits = c(-5, 25)) +
    coord_trans(y = magnify_trans(intercept = 44, reducer = 20))

如果需要的话,可以在x轴上使用相同的变换:

The same transformation can be used on the x axis, if that's what you want:

ggplot(data.frame(x = c(-10, 30), y = c(0, 250)), aes(x, y)) +
    stat_function(fun = function(x) 12 + 180 / (1 + exp(-.759 * (x - 7.69))),
                  size = 2,
                  color = "yellow") +
    coord_cartesian(ylim = c(0, 250))+
    geom_abline(intercept = 44, slope = 0, lty = 2)+
    scale_x_continuous(limits = c(-5, 25)) +
    coord_trans(x = magnify_trans(intercept = 5.675, reducer = 20))

这篇关于ggplot中的压缩轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆