当我有一个分类变量y时,我想避免geom_point的垂直重叠。
library(tidyverse)
# all possible points
df <- expand.grid(
y_factor = paste0('factor_',1:5),
x =1:100
)%>%as.tbl
# randomly missing and overlapping points
# every green point has a pink point underneath, and every blue point
# has a green point underneath it.
seed<-1
df_with_overlap<-df%>%
sample_frac(0.5,replace = TRUE)%>%
group_by(y_factor,x)%>%
mutate(n=factor(1:n()))
p<-ggplot(data=df_with_overlap, aes(x=x, y=y_factor, col=n))
p+geom_point()
使用position_dodge
进行水平隐藏不起作用,因为该轴上的数据太拥挤,因此有些点仍然重叠,可视化不清晰。
p+geom_point(position=position_dodge(width=1))+
ggtitle('position_dodge isnt what Im looking for.
\nx-axis too crowded and points still overlap')
position_jitter
的工作原理是因为我可以将x抖动限制为0,并控制y抖动的程度。但抖动的随机性使其不那么吸引人。我可以在它们存在时识别出3种颜色。
p+geom_point(aes(col=n), position=position_jitter(width=0, height=0.05))+
ggtitle('Jitter kind of works.
\nIt would work better if it wasnt random
\nlike position_dodge, but vertical dodging')
有没有办法垂直避开这些点?
2条答案
按热度按时间c9x0cxw01#
感谢@aosmith推荐
ggstance::position_dodgev()
,这正是我想要的,我增加了过采样,所以效果更明显。wnavrhmk2#
我会将
y_factor
转换为数值,并使用连续的y轴。技巧是按n组添加“噪声”y数值。