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

时间:2019-07-30 09:50:34

标签: r ggplot2 ggrepel

我正在使用ggrepel在二维图中写一些名字。还有一些额外的注释,我已经注意到,对于完全相同的代码,某些运行两次重叠,而某些运行则没有。尤其糟糕的是,它实际上改变了我的绘图页边距,并且以不与其他字冲突的单词进行,因此ggrepel不应四处移动。

如果我使用geom_text而不是geom_text_repel,问题就消失了,或者我也设置了一个种子,但是由于种种原因,我什么都不做。我知道ggrepel必须具有随机成分来随机排列名称,但是我不知道这如何改变我的地块限制。 这是一个示例代码,您需要运行几次以查看区别(您将在右上角看到,Sirius B.在某些运行中与“争议”发生冲突,而在其他运行中则没有冲突)。

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。

1 个答案:

答案 0 :(得分:2)

geom_text_repel确实具有随机成分,并且它根据其创建的文本位置来更改图的限制。您可以使用{{1}内的参数seed(将其传递到set.seedxlimylim(默认值为NA)来控制这两个参数}}。

这将在您的地块限制内始终创建相同的地块:

geom_text_repel