R语言 分类尺度上geom_point的position_dodge的垂直等效项

mrzz3bfm  于 2023-04-09  发布在  其他
关注(0)|答案(2)|浏览(165)

当我有一个分类变量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')

有没有办法垂直避开这些点?

c9x0cxw0

c9x0cxw01#

感谢@aosmith推荐ggstance::position_dodgev(),这正是我想要的,我增加了过采样,所以效果更明显。

df <- expand.grid(
  y_factor = paste0('factor_',1:5),
  x =1:100
)%>%as.tbl

seed<-1
df_with_overlap<-df%>%
  sample_frac(1.5,replace = TRUE)%>%
  group_by(y_factor,x)%>%
  mutate(n=factor(1:n()))

ggplot(data=df_with_overlap, aes(x=x, y=y_factor, col=n))+
  geom_point(position=ggstance::position_dodgev(height=0.3))

wnavrhmk

wnavrhmk2#

我会将y_factor转换为数值,并使用连续的y轴。技巧是按n组添加“噪声”y数值。

df_with_overlap <- df_with_overlap %>%
    # Transform y factors to numbers
    mutate(y_num = as.numeric(y_factor)) %>%
    # Add scaling factor by n group 
    mutate(y_num = y_num + case_when(n == 1 ~  0,
                                     n == 2 ~ -0.1,
                                     n == 3 ~  0.1))

# Plot y numeric values
ggplot(df_with_overlap, aes(x, y_num, color = n)) + 
    geom_point() +
    # On y-axis put original labels and no one will notice that it's actually a continuous scale
    scale_y_continuous(breaks = 1:5, 
                       labels = levels(df_with_overlap$y_factor)) +
    labs(y = "y_factor")

相关问题