如何抖动/删除geom_text标签的重叠

问题描述:

在图中,是否可以使状态缩写标签有些抖动,以免它们重叠?如果我使用check_overlap = TRUE,则它将删除一些重叠的观察结果,而我不希望如此.我也不想要geom_label_repel,因为它的标签会伸出来并穿过我所包括的45度线(我不想发生这种情况)

In the figure, is it possible to jitter the state abbreviation labels a bit so they don't overlap? If I use check_overlap = TRUE, then it removes some observations that overlap, and I don't want that. I also don't want the geom_label_repel, since it has the labels stick out and move across the 45 degree line I included (which I don't want to happen)

这是我的代码的相关部分供参考:

Here's the pertinent part of my code for reference:

ggplot(df, aes(x = huff_margin_dem, y = margin16dem_state, label = abbrev)) +
  geom_abline(intercept = 0) +
  geom_text(fontface = "bold")

您是否尝试过position=position_jitter()?您可以根据自己的选择调整widthheight.

Have you tried position=position_jitter()? You can adjust the width and height to your choosing.

ggplot(df, aes(x = huff_margin_dem, y = margin16dem_state, label = abbrev)) +
  geom_abline(intercept = 0) +
  geom_text(fontface = "bold",position=position_jitter(width=1,height=1))

编辑 仅操作特定标签的示例

EDIT An example to manipulate a certain label only

+geom_text(fontface = "bold",
position=position_jitter(width=ifelse(df$abbrev=='KS',1,0),
      height=ifelse(df$abbrev=='KS',1,0)))

或多个标签

df$jit<-with(df, ifelse(abbrev == "KS" | abbrev == "LA", 1, 2))

+geom_text(fontface = "bold",
    position=position_jitter(width=df$jit,height=df$jit))