ggrepel 更改绘图限制并对同一代码的多次运行进行不同的处理

ggrepel changes plot limits and does it differently for multiple runs of the same code

我正在使用 ggrepel 在二维图中写一些名字。还有一些额外的注释,我注意到,对于完全相同的代码,对于某些 运行s,两者重叠,对于某些 运行s,它们不重叠。特别糟糕的是,它实际上改变了我的情节边距,并且是在一个不与任何其他冲突的词上进行的,因此 ggrepel 不应该四处移动。

如果我使用 geom_text 而不是 geom_text_repel 问题就会消失,或者如果我也设置了种子,但由于各种原因我无法做到。我知道 ggrepel 必须有一个随机组件来随机排列名称,但我不明白这会如何改变我的绘图限制。 这是一个示例代码,您需要 运行 几次才能看到差异(您会在右上角看到,Sirius B. 与 "Controvers" 冲突一些 运行 s 而不是其他人)。

require(ggplot2)
require(ggrepel)
#set.seed(1)
# sample data
a = c(5, 6, 7, 6, 24, 4, 3, 5, 26, 8, 13, 4, 8, 11, 0, 11, 7, 5, 3, 10, 11, 8)
b = c(16 ,19 ,17 ,17 ,21 ,11 ,8 ,11 ,32 ,11 ,24 ,14 ,11 ,17 ,14 ,24 ,14 ,11 ,12 ,18 ,12 ,21)
noms = c("Hermione G." ,"Neville L." ,"Luna L." ,"Ron W." ,"Ginny W." ,"Percy W." ,"Lilly P." ,"Seamus F." ,"Sirius B." ,"Dean T." ,"Draco M." ,"Harry P." ,"Xo X." ,"Viktor K." ,"Hannah A." ,"Susan B." ,"Pansy P." ,"Fleur D." ,"Cormac M." ,"Cedric D." ,"Fay D." ,"Maisy R.")

# this is just to reproduce my exact results
df = cbind.data.frame(a, b, noms)
df[, 1] = scale(df[, 1])
df[, 2] = scale(df[, 2])

max_y = max(max(df[, 1]), abs(min(df[, 1])))
max_x = max(max(df[, 2]), abs(min(df[, 2])))
# actual plot
ggplot(df, aes(x = df[, 2], y = df[, 1], label = noms)) + 
  geom_text_repel(fontface = "bold") + 
  geom_text(aes(x = max_x - 0.25, y = max_y - 0.15, label = "Controvers"), fontface = "italic", angle = 40) +
  xlim(c(-max_x - .1, max_x + .1)) + 
  ylim(c(-max_y - .1, max_y + .1)) +
  theme_void() + 
  ggsave(file = "file.pdf", dpi = 1200, width = 25, height = 20, units = "cm") 

我在 Windows 10.

上使用 R 3.5.3、ggplot2 3.1.1 和 ggrepel 0.8.1

geom_text_repel 确实有一个随机成分,它会根据它创建的文本位置更改绘图的限制。您可以使用参数 seed(传递给 set.seed)、xlimylim(默认值为 NA)在 [=11] 中进行控制=]打电话。

这会在您的绘图限制内始终创建相同的绘图:

ggplot(df, aes(x = df[, 2], y = df[, 1], label = noms)) + 
  geom_text_repel(fontface = "bold", seed = 1, 
                  xlim = c(-max_x - .1, max_x + .1),
                  ylim = c(-max_y - .1, max_y + .1)) + 
  geom_text(aes(x = max_x - 0.25, y = max_y - 0.15, label = "Controvers"), fontface = "italic", angle = 40) +
  xlim(c(-max_x - .1, max_x + .1)) + 
  ylim(c(-max_y - .1, max_y + .1)) +
  theme_void() + 
  ggsave(file = "file.pdf", dpi = 1200, width = 25, height = 20, units = "cm")