I am new to RDFLIB in python. I found this example of creating a graph on here. What is the simplest way to visualize graph created by this code?
JavaScript
x
27
27
1
import rdflib
2
# Now we create a graph, a representaiton of the ontology
3
g = rdflib.Graph()
4
5
# Now define the key words that we will use (the edge weights of the graph)
6
has_border_with = rdflib.URIRef('http://www.example.org/has_border_with')
7
located_in = rdflib.URIRef('http://www.example.org/located_in')
8
9
# define the things - base level objects that will be the nodes
10
# In this case first we have countries
11
germany = rdflib.URIRef('http://www.example.org/country1')
12
france = rdflib.URIRef('http://www.example.org/country2')
13
china = rdflib.URIRef('http://www.example.org/country3')
14
mongolia = rdflib.URIRef('http://www.example.org/country4')
15
16
# then we have continents
17
europa = rdflib.URIRef('http://www.example.org/part1')
18
asia = rdflib.URIRef('http://www.example.org/part2')
19
20
# Having defined the things and the edge weights, now assemble the graph
21
g.add((germany,has_border_with,france))
22
g.add((china,has_border_with,mongolia))
23
g.add((germany,located_in,europa))
24
g.add((france,located_in,europa))
25
g.add((china,located_in,asia))
26
g.add((mongolia,located_in,asia))
27
I see that the rdflib package has a tools component that has a function called rdfs2dot. How can I use this function to display a plot with the RDF graph in it?
Advertisement
Answer
Using the hint in this question: https://www.researchgate.net/post/Is_there_any_open_source_RDF_graph_converter
I was able to plot the RDF Graph by converting to Networkx Graph and using the Networkx/Matplotlib plotting tools.
JavaScript
1
21
21
1
import rdflib
2
from rdflib.extras.external_graph_libs import rdflib_to_networkx_multidigraph
3
import networkx as nx
4
import matplotlib.pyplot as plt
5
6
url = 'https://www.w3.org/TeamSubmission/turtle/tests/test-30.ttl'
7
8
g = rdflib.Graph()
9
result = g.parse(url, format='turtle')
10
11
G = rdflib_to_networkx_multidigraph(result)
12
13
# Plot Networkx instance of RDF Graph
14
pos = nx.spring_layout(G, scale=2)
15
edge_labels = nx.get_edge_attributes(G, 'r')
16
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
17
nx.draw(G, with_labels=True)
18
19
#if not in interactive mode for
20
plt.show()
21
To visualise large RDF Graphs the styling might need some finetuning ;-)