如何在R中使用ggplot2根据阈值对散点图点着色?
要使用ggplot2根据阈值对散点图点着色,我们首先需要定义一个包含阈值列,然后我们可以在aes中使用该列进行着色。可以使用cut函数创建阈值列。
查看下面给出的示例,了解如何操作。
示例
以下代码片段创建一个示例数据框:
x<-rpois(20,5) y<-rpois(20,2) df<-data.frame(x,y) df
输出
创建了以下数据框:
x y 1 6 0 2 5 5 3 7 2 4 4 0 5 4 1 6 5 0 7 9 3 8 4 1 9 7 1 10 5 2 11 4 3 12 8 3 13 4 0 14 9 0 15 5 1 16 3 3 17 7 1 18 2 2 19 5 3 20 5 1
要根据y列中的值创建阈值列,请将以下代码添加到上面的代码片段中:
x<-rpois(20,5) y<-rpois(20,2) df<-data.frame(x,y) df$Threshold<-cut(df$y,breaks=c(-Inf,2,Inf),labels=c("<=2",">2")) df
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果将以上所有代码片段作为一个程序执行,则会生成以下输出:
x y Threshold 1 6 0 <=2 2 5 5 >2 3 7 2 <=2 4 4 0 <=2 5 4 1 <=2 6 5 0 <=2 7 9 3 >2 8 4 1 <=2 9 7 1 <=2 10 5 2 <=2 11 4 3 >2 12 8 3 >2 13 4 0 <=2 14 9 0 <=2 15 5 1 <=2 16 3 3 >2 17 7 1 <=2 18 2 2 <=2 19 5 3 >2 20 5 1 <=2
要加载ggplot2包并在x和y之间创建散点图,并根据阈值列显示不同颜色的点,请将以下代码添加到上面的代码片段中:
library(ggplot2) ggplot(df,aes(x,y,color=Threshold))+geom_point()
输出
如果将以上所有代码片段作为一个程序执行,则会生成以下输出:
广告