2

I wrote this script which draws a random 3D graph using NetworkX in python. The output of this script is a 3D figure where I can rotate the camera around the graph structure.

import networkx as nx
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import random
import pickle


def gen_random_3d_graph(n_nodes, radius):
    pos = {i: (random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)) for i in range(n_nodes)}
    graph = nx.random_geometric_graph(n_nodes, radius, pos=pos)
    return graph


def plot_3d_network(graph, angle):
    pos = nx.get_node_attributes(graph, 'pos')

    with plt.style.context("bmh"):
        fig = plt.figure(figsize=(10, 7))
        ax = Axes3D(fig)
        for key, value in pos.items():
            xi = value[0]
            yi = value[1]
            zi = value[2]

            ax.scatter(xi, yi, zi, edgecolor='b', alpha=0.9)
            for i, j in enumerate(graph.edges()):
                x = np.array((pos[j[0]][0], pos[j[1]][0]))
                y = np.array((pos[j[0]][1], pos[j[1]][1]))
                z = np.array((pos[j[0]][2], pos[j[1]][2]))
                ax.plot(x, y, z, c='black', alpha=0.9)
    ax.view_init(30, angle)
    pickle.dump(fig, open('FigureObject.fig.pickle', 'wb'))
    plt.show()


if __name__ == '__main__':

    graph01 = gen_random_3d_graph(15, 0.6)
    plot_3d_network(graph01, 0)

I want to save this graph to view it later using paraview. I tried pickle but it did not work. Is there anyway to view the 3D graph in paraview?

Vebbie
  • 1,669
  • 2
  • 12
  • 18
shahriar
  • 362
  • 4
  • 17

1 Answers1

1

There isn't a common data type between NetworkX and Paraview.

You could write a VTK file very easily by importing vtk into your python environment and creating the graph using vtkLines (check out this example: https://lorensen.github.io/VTKExamples/site/Python/GeometricObjects/ColoredLines/)

Or you could export from NetworkX into JSON and write a Python Programmable Source in Paraview for reading the custom data structure (see these examples https://www.paraview.org/Wiki/Python_Programmable_Filter)

Stuart Buckingham
  • 1,574
  • 16
  • 25
  • Thanks, my goal was transforming a graph's edges to cylinders with appropriate width in 3 dimension. As you suggest i think vtk is more suitable for this problem than NetworkX. – shahriar Jan 15 '19 at 15:49