ggplot 仅显示属于特定级别的点的帕累托前沿

问题描述

正在使用的库

install.packages("rPref")
install.packages("dplyr")
install.packages("igraph")
install.packages("ggplot") 

以 R 中的 mtcars 数据集为例。

为了找到帕累托边界和水平值,首先建立偏好

p <- high(mpg) * high(hp) 

然后计算水平值 w.r.t. p 使用 top-all

res <- psel(mtcars,p,top = nrow(mtcars))

一个人创建如下可视化

gp <- ggplot(res,aes(x = mpg,y = hp,color = factor(.level))) + geom_point(size = 3)

它将显示带有颜色的 mtcars 的 mpg 和 hp 值的图,每种颜色代表级别(接近最佳值)。如下

enter image description here

如果要为下一层所有点的每个区域绘制帕累托前线,可以运行

gp + geom_step(direction = "vh") 

结果是

enter image description here

但是,对于一个人的情况,只有第 1 级是相关的,如何只显示第 1 级的点和特定的帕累托前沿?

factor(.level) 更改为 factor(1)

gp <- ggplot(res,color = factor(1))) + geom_point(size = 3)

给出以下内容,忽略了之前的级别,但一些不属于级别 1 的内容似乎包含在其中

enter image description here

解决方法

这是您要找的吗?

data(mtcars)
p <- high(mtcars$mpg) * high(mtcars$hp) 

res <- psel(mtcars,p,top = nrow(mtcars))
res1 <- res %>% filter(.level == "1")
gp <- ggplot() + 
  geom_point(data = res,aes(x = mpg,y = hp,color = factor(.level)),size = 3) + 
  geom_step(data = res1,aes(x=mpg,y=hp,color=factor(.level)))

enter image description here


编辑以解决评论

这是没有其他点的同一张图:

res %>% filter(.level == "1") %>% 
  ggplot() + 
    geom_point(aes(x = mpg,y = hp),size = 3) + 
    geom_step(aes(x=mpg,y=hp))

enter image description here