Reputation: 51
I'm using igraph to plot networks and can't seem to get nodes (vertices) not drawn over top of each other.
My code:
g<-graph.empty(n=0, directed=FALSE)
nodes<-my_verts
edge<-my_intra_edges
freq<-nodes[,2]
max_freq<-sum(freq)
frequency<-freq*50/max_freq
colour1<-heat.colors(max_freq/2+2)
colour<-rev(colour1)
g<-igraph::add.vertices(g, length(nodes[,2]), name=as.character(nodes[,1]), color=colour[freq/2+2])
names<-V(g)$name
ids<-1:length(names)
names(ids)<-names
from<-as.character(edge[,1])
to<-as.character(edge[,2])
edges<-matrix(c(ids[from], ids[to]), nc=2)
my_weight<-edge[,3]
g<-add.edges(g, t(edges), weight=my_weight)
V(g)$label<-V(g)$name
my_radius<-sqrt(my_verts[,2]/pi)
V(g)$size<-my_radius
V(g)$label.cex<-0.0001
del_ids<-intersect(which(degree(g)==0), which(freq==1))
g1<-delete.vertices(g, ids[del_ids])
length(del_ids)
jpeg(file="BC9.jpeg", height=7016, width=7016, res=600)
par(mfrow=c(1,1), mar=c(5,5,5,5))
title=c("BC9")
layout<-layout_with_graphopt(g1, niter=800)
plot(g1, layout=layout, edge.color="darkblue", main=title, edge.width=0.2)
dev.off()
This currently will plot most nodes as independent points but some nodes get plotted on top of each other. Is there a way to get the nodes to have better spacing? Thanks.
Upvotes: 5
Views: 3438
Reputation: 223
From what I understand, the coordinates for the plots are rescaled, but you can stop that with the rescale
argument and do things manually. You can also use the norm_coords()
to normalize the plot with the boundaries you have. I don't understand all the detail in this, but it works for me.
library(igraph)
g <- barabasi.game(100) # create a graph
lo <- layout_with_kk(g) # create a layout
lo <- norm_coords(lo, ymin=-1, ymax=1, xmin=-1, xmax=1)
# I think this tells igraph to normalize the coordinates of the
# layout relative to the space you're working with
# see how it works
par(mfrow=c(1,2), mar=c(0,0,0,0))
plot(g, edge.arrow.width = .25,
edge.arrow.size = .25,
vertex.label = NA,
vertex.size = 5,
rescale=FALSE,
layout=lo*0.25)
plot(g, edge.arrow.width = .25,
edge.arrow.size = .25,
vertex.label = NA,
vertex.size = 5,
rescale=FALSE,
layout=lo*1)
Created on 2020-09-10 by the reprex package (v0.3.0)
Upvotes: 1
Reputation: 990
I have the same problem with igraph, the layouts these algorithms provide don't seem to prevent overlap of nodes.
Someone will probably come up with a good igraph-only solution but my very tedious current workaround for this is: I open the network on Gephi, then I use Force Atlas 2 algorithm with the "prevent overlap" option checked, I save the .gexf file, then later I extract the x
,y
,z
coordinates from the file, then I use it as the layout in igraph.
Upvotes: 1