Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 根据x和y值指定点颜色_R_Ggplot2 - Fatal编程技术网

R 根据x和y值指定点颜色

R 根据x和y值指定点颜色,r,ggplot2,R,Ggplot2,我想知道是否可以根据ggplot2中的x和y值指定点颜色 例如,我想分配点,其中(x

我想知道是否可以根据ggplot2中的x和y值指定点颜色

例如,我想分配点,其中(x<0.75&y<2)为红色;其中(0.75试试这个:

library(dplyr)
library(ggplot2)

my_data <- iris %>% 
  mutate(width_length = paste0(cut(Petal.Width, c(0, 0.75, 2.25, Inf), right=FALSE), ' _ ',
                              cut(Petal.Length, c(0, 2, 4, Inf), right=FALSE)))
ggplot(my_data) + 
  geom_point(aes(x = Petal.Width, 
                 y = Petal.Length, 
                 color = width_length))
库(dplyr)
图书馆(GG2)
我的_数据%
mutate(width_length=paste0(cut(Petal.width,c(0,0.75,2.25,Inf),right=FALSE),',
剪切(花瓣长度,c(0,2,4,Inf),右=假)
ggplot(我的_数据)+
几何点(aes(x=花瓣宽度,
y=花瓣长度,
颜色=宽度(单位长度))
输出:

要扩展我的评论,请根据条件创建自定义颜色列,并将col参数与
比例\u颜色\u标识一起使用

library(ggplot2)

# Make a custom colour column based on conditions
# here I used one condition, you can keep nesting ifelse for more conditions
iris$myCol <- ifelse(iris$Petal.Width < 0.75 & iris$Petal.Length, "red", "green")

ggplot(iris) + 
  geom_point(data = iris, 
             aes(x = Petal.Width, y = Petal.Length, col = myCol)) +
  scale_colour_identity()
库(ggplot2)

#根据条件制作自定义颜色列 #在这里,我使用了一个条件,您可以继续嵌套其他条件
iris$myCol如果您只需要此着色信息一次,只需在绘图之前使用此变量临时扩展iris,使IMHO代码更清晰

library(dplyr)
library(ggplot2)

iris %>%
    mutate(width_length = 
        paste0(cut(Petal.Width, c(0, 0.75, 2.25, Inf), right=FALSE), 
        ' _ ',
        cut(Petal.Length, c(0, 2, 4, Inf), right=FALSE)))
ggplot() + 
    geom_point(aes(x = Petal.Width, 
             y = Petal.Length, 
             color = width_length))   

这样,您就不会弄乱您的工作区,因为您只使用了一个数据框,但仍然保留了该数据框。

根据条件创建一个自定义颜色列,例如:
myData$mycl小心这些条件,例如当您说
(2.25=4)时绿色。
您的意思是
2.25=4
还是
2.25=4
?因为您在此处标记为绿色的点不适合第一种情况。我能想到的最佳方法是使用组规范向数据中添加一列,然后打印。@DS_UNI,谢谢,我的意思是“和”,我已编辑了我的问题。@zx8754非常感谢您的帮助。@Dong在这种情况下,iris数据集将有四个组,而不是三个组,我将发布一个示例代码作为答案,供您尝试在调用
ggplot()
之前缺少一个管道操作员
%%
library(dplyr)
library(ggplot2)

iris %>%
    mutate(width_length = 
        paste0(cut(Petal.Width, c(0, 0.75, 2.25, Inf), right=FALSE), 
        ' _ ',
        cut(Petal.Length, c(0, 2, 4, Inf), right=FALSE)))
ggplot() + 
    geom_point(aes(x = Petal.Width, 
             y = Petal.Length, 
             color = width_length))