R: custom ggplot2 color-transform gives error in labels

大憨熊 提交于 2019-12-11 08:58:04

问题


Basically, i have a dataframe with 3 numeric vectors(x,y,z), and lets say i wanna make a scatter plot of x,y colored by z. I want to transform the colorscale with a squareroot that respects sign, so i made my own with trans_new. Here is a simple dataset, but with the actual transform.

library(ggplot2)
library(scales)
set.seed(1)

plot<-data.frame(x=rnorm(100),y=rnorm(100),z=rnorm(100))
super_trans <- function(){
trans_new('super', function(X) sapply(X,function(x) {if(x>0){x^0.5} else{-(-    x)^0.5}}), function(X) sapply(X,function(x){ if(x>0){x^2} else{-x^2}}))
}
ggplot(plot,aes(x,y))+geom_point(aes(colour=z))+scale_colour_gradient(trans="super")

It gives an error,

Error in if (x > 0) { : missing value where TRUE/FALSE needed 

I don't understand it. I tried to backtrack the mistake, and my guess is that the error happens when trans_new tries to make breaks. However, i do not understand how the "breaks" parameter works in trans_new. Is there a ggplot2/Scales hero out there, that can help me transform my color-scale correctly?

It may be relevant that only some datasets gives errors.


回答1:


There is a vectorized if, called ifelse. It also seems you are missing an extra minus.

super_trans <- function() {
     trans_new('super', 
               function(x) ifelse(x>0, x^0.5, -(-x)^0.5), 
               function(x) ifelse(x>0, x^2, -(-x)^2))
}



来源:https://stackoverflow.com/questions/30580506/r-custom-ggplot2-color-transform-gives-error-in-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!