簡體   English   中英

在 Python 中可視化 RDFLIB 圖形

[英]Visualize an RDFLIB Graph in Python

我是 Python RDFLIB 的新手。 我在這里找到了這個創建圖表的例子。 可視化此代碼創建的圖形的最簡單方法是什么?

import rdflib
# Now we create a graph, a representaiton of the ontology
g = rdflib.Graph()

# Now define the key words that we will use (the edge weights of the graph)
has_border_with = rdflib.URIRef('http://www.example.org/has_border_with')
located_in = rdflib.URIRef('http://www.example.org/located_in')

# define the things - base level objects that will be the nodes
# In this case first we have countries
germany = rdflib.URIRef('http://www.example.org/country1')
france = rdflib.URIRef('http://www.example.org/country2')
china = rdflib.URIRef('http://www.example.org/country3')
mongolia = rdflib.URIRef('http://www.example.org/country4')

# then we have continents
europa = rdflib.URIRef('http://www.example.org/part1')
asia = rdflib.URIRef('http://www.example.org/part2')

# Having defined the things and the edge weights, now assemble the graph
g.add((germany,has_border_with,france))
g.add((china,has_border_with,mongolia))
g.add((germany,located_in,europa))
g.add((france,located_in,europa))
g.add((china,located_in,asia))
g.add((mongolia,located_in,asia))

我看到 rdflib 包有一個工具組件,它有一個名為 rdfs2dot 的函數。 如何使用此函數顯示帶有 RDF 圖形的繪圖?

使用這個問題中的提示: https : //www.researchgate.net/post/Is_there_any_open_source_RDF_graph_converter

我能夠通過轉換為 Networkx Graph 並使用 Networkx/Matplotlib 繪圖工具來繪制 RDF Graph。

import rdflib
from rdflib.extras.external_graph_libs import rdflib_to_networkx_multidigraph
import networkx as nx
import matplotlib.pyplot as plt

url = 'https://www.w3.org/TeamSubmission/turtle/tests/test-30.ttl'

g = rdflib.Graph()
result = g.parse(url, format='turtle')

G = rdflib_to_networkx_multidigraph(result)

# Plot Networkx instance of RDF Graph
pos = nx.spring_layout(G, scale=2)
edge_labels = nx.get_edge_attributes(G, 'r')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw(G, with_labels=True)

#if not in interactive mode for 
plt.show()

要可視化大型 RDF 圖形,樣式可能需要一些微調 ;-)

我可以按照你的建議用 rdf2dot 制作你的 RDF Graph 的圖片。 盡管如此,我對那個庫並不完全滿意,因為它沒有為文字制作節點。 這是我的代碼:

!pip install pydotplus
!pip install graphviz

import io
import pydotplus
from IPython.display import display, Image
from rdflib.tools.rdf2dot import rdf2dot

def visualize(g):
    stream = io.StringIO()
    rdf2dot(g, stream, opts = {display})
    dg = pydotplus.graph_from_dot_data(stream.getvalue())
    png = dg.create_png()
    display(Image(png))

visualize(g)

給出以下結果: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM