Every once in a while, people e-mail me with questions about netplot, and probably the most frequently asked question is how to convert data from an adjacency matrix into an edgelist, which is the data format that netplot expects. I finally took the time to write some decent code to do it, and I might as well share it here. In principle it’s quite simple. If you want your data as a simple edgelist (or arclist, strictly speaking), a reshape command is almost all that you need. However, isolated nodes will not show up in the resulting edgelist. If you want to create an “extended edgelist” that includes also isolates nodes (for example because you want them to be drawn by netplot), things become slightly more complicated. In the code below, section #3 is dedicated to solving that problem; I you don’t want or need it, you can just skip that part. My feeling is that section #3 could be further simplified; suggestions are welcome!
// #1 Example dataset; random adjacency matrix with N=4; node 4 is isolated
clear set seed 223344 set obs 4forval x = 1(1)4{ gen v`x' =(uniform()>.5) replace v`x'=0 if _n==`x' replace v`x' = 0 if _n == 4 } replace v4 = 0 gen n1 = _n
list // #2 Transform into edgelist reshape long v, i(n1) j(n2) // #3 This section only to keep isolates in the data. Skip if you want a // regular edgelist without isolates. gen id_arc = _n bys n1: egen degree1 = total(v) bys n2: egen degree2 = total(v) sort n1 reshape long n degree, i(id_arc) j(nseq) bys n: egen totaldegree = total(degree) gen isolated = totaldegree == 0 drop totaldegree reshape wide n degree isolated, i(id_arc) j(nseq) replace n2 = . if isolated1 == 1 bys n1: gen tag = _n==1 drop if isolated1 & tag==0 drop isolated* keep n1 n2 v // #4 keep if v==1 | n2==. drop v list // Tada! netplot n1 n2,label arrows // draw the network!