R:如何在ggplot2中同时反转并应用转换到轴

时间:2017-10-10 22:17:24

标签: r ggplot2 scaletransform

在使用ggplot2包构建的图中,例如:

ggplot(cars, aes(x = speed, y = dist))+geom_col()

可以通过应用适当的指令来转换轴。例如,+scale_y_continuous(trans="reverse")从顶部向底部绘制坐标轴,scale_y_continuous(trans="sqrt")进行非线性变换。我需要将两个函数组合在一起,即在顶部有轴原点,在y轴上有log或sqrt变换。逐个应用转换(即+scale_y_reverse() ... + scale_y_log())会发出警告:Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.

1 个答案:

答案 0 :(得分:1)

这个怎么样:

require(scales);
rev_sqrt_trans <- function() {
    scales::trans_new(
        name = "rev_sqrt", 
        transform = function(x) -sqrt(abs(x)), 
        inverse = function(x) x^2);
}

require(ggplot2);
ggplot(cars, aes(x = speed, y = dist)) + geom_col() + scale_y_continuous(trans = "rev_sqrt")

您可以在定义新转化时优化中断,请参阅?trans_new

enter image description here