The following code changed from VTKUsersGuide

from vtk import *

# create a random graph
source = vtkRandomGraphSource()
source.SetNumberOfVertices(100)
source.SetNumberOfEdges(110)
source.StartWithTreeOn()
source.Update()

# setup a strategy for laying out the graph
# NOTE: You can set additional options for each strategy, as desired
#strategy = vtkFast2DLayoutStrategy()
strategy = vtkRandomLayoutStrategy()
strategy.SetGraphBounds( 0, 200, 0, 200, 0, 200 )
strategy.SetThreeDimensionalLayout( True )
#strategy = vtkSimple2DLayoutStrategy()
#strategy = vtkCosmicTreeLayoutStrategy()
#strategy = vtkForceDirectedLayoutStrategy()
#strategy = vtkTreeLayoutStrategy()

# set the strategy on the layout
layout = vtkGraphLayout()
layout.SetLayoutStrategy(strategy)
layout.SetInputConnection(source.GetOutputPort())

# create the renderer to help in sizing glyphs for the vertices
ren = vtkRenderer()

# Pipeline for displaying vertices - glyph -> mapper -> actor -> display # mark each vertex with a special glyph
vertex_glyphs = vtkGraphToGlyphs()
vertex_glyphs.SetInputConnection(layout.GetOutputPort())
vertex_glyphs.SetGlyphType(9)
vertex_glyphs.FilledOn()
vertex_glyphs.SetRenderer(ren)

# create a mapper for vertex display
vertex_mapper = vtkPolyDataMapper()
vertex_mapper.SetInputConnection( vertex_glyphs.GetOutputPort() )
vertex_mapper.SetScalarRange( 0, 100 )
vertex_mapper.SetScalarModeToUsePointFieldData()
vertex_mapper.SelectColorArray("vertex id")

# create the actor for displaying vertices
vertex_actor = vtkActor()
vertex_actor.SetMapper( vertex_mapper )

# Pipeline for displaying edges of the graph - layout -> lines -> mapper -> actor -> display
# NOTE: If no edge layout is performed, all edges will be rendered as # line segments between vertices in the graph.
edge_strategy = vtkArcParallelEdgeStrategy()
edge_layout = vtkEdgeLayout()
edge_layout.SetLayoutStrategy( edge_strategy )
edge_layout.SetInputConnection( layout.GetOutputPort() )
edge_geom = vtkGraphToPolyData()
edge_geom.SetInputConnection( edge_layout.GetOutputPort() )

# create a mapper for edge display
edge_mapper = vtkPolyDataMapper()
edge_mapper.SetInputConnection( edge_geom.GetOutputPort() )

# create the actor for displaying the edges
edge_actor = vtkActor()
edge_actor.SetMapper( edge_mapper )
edge_actor.GetProperty().SetColor( 0., 1., 0. )
edge_actor.GetProperty().SetOpacity(0.25)

ren.AddActor( edge_actor )
ren.AddActor( vertex_actor )
ren.SetBackground( 0, 0, 0 )

renWin = vtk.vtkRenderWindow()
renWin.AddRenderer( ren )

renWinInteractor = vtk.vtkRenderWindowInteractor()
renWinInteractor.SetRenderWindow( renWin )
renWinInteractor.Start()



Categories: Python

Leave a Reply

Your email address will not be published. Required fields are marked *