GraphPlot.jl icon indicating copy to clipboard operation
GraphPlot.jl copied to clipboard

document ability to pass x,y locations to gplot

Open sbromberger opened this issue 7 years ago • 4 comments

Inspired by a stackoverflow question.

It would be nice to allow the vertices' positions to be specified by, say, a vector of (x, y) tuples, which are then normalized to whatever canvas is being used and plotted.

sbromberger avatar Mar 19 '19 01:03 sbromberger

Turns out this functionality is present but it should really be in README.md.

sbromberger avatar Mar 19 '19 16:03 sbromberger

To get the locations you can use:

locs_x, locs_y = spring_layout(g)

(or any other layout) and then you can change the positions (they are normalized between -1, 1) or use entirely your own (they will be normalized internally) with:

gplot(g, locs_x, locs_y)

Hope that helps someone.

Wikunia avatar Aug 02 '19 13:08 Wikunia

Here you go:

# Load the adjacency matrix and graph attributes
mat_arcTwoNodes = [0    1    0    0    0    0    0    0    0    0;
0    0    0    0    0    1    0    0    0    0;
0    0    0    0    0    0    0    0    0    1;
1    0    0    0    1    0    0    0    0    0;
0    0    0    0    0    1    0    0    0    0;
1    0    0    1    0    0    0    1    0    0;
0    1    1    0    0    0    0    0    0    0;
0    0    0    0    0    0    0    0    1    0;
0    0    0    0    1    0    0    0    0    0;
0    0    0    0    0    1    1    0    1    0]
vec_xNode = [1    3    8    2    4    5    6    7    9    9]
vec_yNode = [1    2    1    7    9    5    3    7    9    4]

# Load the packages
using LightGraphs, GraphPlot, MetaGraphs, GraphRecipes, Plots
# Create a generic graph
gr = SimpleDiGraph()
add_vertices!(gr, size(mat_arcTwoNodes, 1))
# Add edges based on the adjacency matrix
for i in 1:size(mat_arcTwoNodes, 1), j in 1:size(mat_arcTwoNodes, 2)
    if mat_arcTwoNodes[i,j] != 0
        add_edge!(gr, i, j)
    else
        nothing
    end
end
# Attach the metagraph to the original graph
mgr = MetaDiGraph(gr)
# Add the attribute of nodes
for i in 1:size(mat_arcTwoNodes,1)
    set_props!(mgr, i, Dict(
        Symbol("vec_xNode") => vec_xNode[i],
        Symbol("vec_yNode") => vec_yNode[i]
        ))
end
# Plot the graph
graphplot(gr, x=vec_xNode, y=vec_yNode)

The result is going to be as follow: enter image description here

You may add other attributes to the plot (ask graphplot). I answered this question on stack overflow: https://stackoverflow.com/questions/55228773/plot-the-directed-graph-in-julia-with-vertices-in-fixed-positions-by-x-y-coordin/69485233#69485233

ghost avatar Oct 07 '21 17:10 ghost

I think we can close this issue

hdavid16 avatar Jul 27 '22 17:07 hdavid16