问题描述
如果满足条件,我正在寻找一种填充 geom_point 的方法
示例:
mydata <- tibble(x_var = 1:5,y_var = runif(5),category_a = c('yes','yes','no','yes'),category_b = c('down','up','down','down')
)
ggplot(mydata,aes(x = x_var,y = y_var,color = category_a,)
) +
geom_point(shape = 21,size = 5,stroke = 2
)
我想把满足条件category_b == 'down'
的点用与category_a
相同的颜色填好,剩下的不填,我该怎么做?
问候!
解决方法
您可以在 fill
参数中添加填充条件。并用 scale_fill_discrete
添加透明色。
代码
mydata <- tibble(x_var = 1:5,y_var = runif(5),category_a = c('yes','yes','no','yes'),category_b = c('down','up','down','down')
)
ggplot(mydata,aes(x = x_var,y = y_var,color = category_a,fill = ifelse(category_b == "down",category_a,NA)
)
) +
geom_point(size = 5,shape = 21,stroke = 2) +
scale_fill_discrete(na.value = "transparent") +
guides(fill = FALSE)
,
另一种方法是使用特定形状并手动分配它们。一个不错的副作用是更具描述性的图例:
mydata <- tibble(x_var = 1:5,'down'))
# choose circle and dot shapes
shps <- c(1,16)
ggplot(mydata,y = y_var,shape= category_b)) +
geom_point(size = 5,stroke = 2) +
# add manually choosen shapes and colors
scale_shape_manual(values=shapes)