我最近研究了Collatz Conjecture,并试图提出一种方法来计算给定数导致1的向量,并一次可视化多个向量。但是,我无法弄清楚如何为图形提供一个好的布局。理想情况下,我想要一个像this或this这样的图形。
这是我的工作
1)计算Collatz值的功能
Collatz <- function(x){
# checking whether the number is a mathematical integer
if(round(x) != x){
warning("x must be an integer larger than 1")
break
}
# initializing output vector
vec <- integer()
vec[1] <- x
# checking whether the input is valid
if(x > 0){
# continuing computation until we get a 1 in the vector
while( 1 %in% vec == FALSE){
# when the last element of the vector is even
if(vec[length(vec)] %% 2 == 0){
# initilaize a new element in vec by dividing the previous one by 2
vec[length(vec)+1] <- vec[length(vec)]/2
}
# when the last element of the vector is odd
if(vec[length(vec)] %% 2 != 0){
# initilaize a new element in vec by multiplying the previous one with 3 and adding 1
vec[length(vec)+1] <- 3*vec[length(vec)]+1
}
}
} else(warning("x must be an integer larger than 1"))
# returning output vector except for the last element (which will be 4 insted of 1 due to the while loop)
return(vec[-length(vec)])
}
2)用于为设定范围内的所有向量创建图形的功能
CollatzGraphing <- function(x){
# loading igraph library
library(igraph)
Numbers <- 1:x
List <- sapply(Numbers,Collatz)
# sorting list by length and removing empty lists
x <- List[order(sapply(List,length),decreasing=T)]
x <- x[sapply(x,length) >= 2]
# transforming the vectors into graph format
x <- lapply(x, rep, each = 2)
x <- lapply(x, function(y){y[-c(1,length(y))]})
x <- lapply(x, function(y){as.character(y)})
# transforming the prepared vectors into graph objects
x <- lapply(x, graph, directed=TRUE)
# creating a union of all graph objects
CompleteGraph <- do.call(union, x)
# plotting graph
Plot <- plot(CompleteGraph,
vertex.size = 5,
edge.arrow.size=.1,
vertex.label.cex = 0.5,
vertex.color = "white")
# returning graph object
return(CompleteGraph)
}
当我在不指定任何布局的情况下使用第二个函数时,会得到如下信息:
Graph1 <- CollatzGraphing(20)
当我尝试使用不同的布局时,图形看起来与我的目标完全不同
V(Graph1)
plot(Graph1,
vertex.size = 5,
edge.arrow.size=.1,
vertex.label.cex = 0.5,
vertex.color = "white",
layout = layout_as_tree(Graph1, circular = TRUE, root = 21))
igraph中是否有一种布局可以创建与我一开始所链接的结构相似的结构?