R:自定义ggplot2颜色转换给标签中的错误 [英] R: custom ggplot2 color-transform gives error in labels

查看:196
本文介绍了R:自定义ggplot2颜色转换给标签中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个有3个数字向量(x,y,z)的数据框,并且可以说我想创建x,y的散点图。我想用一个尊重符号的平方根来转换颜色比例,所以我用trans_new创建了我自己的颜色比例。

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

plot <-data.frame(x = rnorm(100),y = rnorm(100),z = rnorm(100))
super_trans< ;函数(){
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 aes(x,y))+ geom_point(aes(color = z))+ scale_colour_gradient(trans =super)

它给出一个错误,

  if(x> 0)中的错误{:missing value where TRUE / FALSE需要

我不明白。我试图回溯这个错误,我的猜测是,当trans_new试图休息时发生错误。
但是,我不明白trans_new中的中断参数是如何工作的。
是否有ggplot2 / Scales英雄出现,可以帮助我正确转换颜色比例?

可能相关的是,只有某些数据集出现错误。

解决方案

如果有一个向量化的,称为 ifelse 。它也似乎你错过了一个额外的减。

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


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.

解决方案

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

这篇关于R:自定义ggplot2颜色转换给标签中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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