1

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

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

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。

4

1 回答 1

2

geom_text_repel确实有一个随机分量,它会根据它创建的文本位置更改绘图的限制。您可以使用调用内部的参数seed(传递给set.seedxlim、 和ylim(默认为)来控制两者。NAgeom_text_repel

这会在您的绘图范围内始终创建相同的绘图:

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")
于 2019-07-30T10:01:57.413 回答