Visualization Options in Semantica’s KGVisualizer and OntologyVisualizer: A Complete Guide
Semantica provides two specialized visualization components—KGVisualizer for generic knowledge graphs and OntologyVisualizer for hierarchical ontologies—both offering configurable layouts, interactive controls, and multi-format export capabilities via the PyVis library.
The semantica-agi/semantica repository ships with dedicated visualization modules that transform RDF data and semantic networks into interactive, web-based graphics. Understanding these visualization options allows developers to inspect complex graph structures, explore ontology hierarchies with depth control, and generate publication-ready static assets directly from Python.
KGVisualizer Layout and Styling Options
The KGVisualizer class, implemented in semantica/visualization/kg_visualizer.py, provides a flexible interface for rendering any SemanticNetwork object. It constructs a pyvis.network.Network instance and exposes granular controls for physics-based positioning, aesthetic styling, and user interactivity.
Layout Engines
The visualizer supports three distinct layout algorithms selectable via the layout parameter:
- Spring – Force-directed positioning that simulates physical attraction and repulsion between nodes, ideal for revealing community structures in dense graphs.
- Circular – Arranges nodes in a ring formation, useful for comparing relational density around central entities.
- Hierarchical – Dot-style tree layout (
layout="hierarchical") that emphasizes directed flows and parent-child relationships.
The layout engine is applied during the network initialization phase before node traversal begins.
Node and Edge Customization
Visual aesthetics are controlled through dictionary parameters passed to the constructor:
node_style– Defines per-node attributes includingcolor,shape(e.g., "dot", "box"), andsizebased on graph properties or categorical mappings.edge_style– Configureswidth,color, andarrowsdirectionality, with automatic scaling available based on edge weight or relation type.
The class iterates over the source graph to attach these style dictionaries to the underlying PyVis network object, ensuring consistent rendering across export formats.
Interactive Controls
The KGVisualizer enables exploratory data analysis through several interactive features:
- Zoom and pan – Standard canvas navigation available in the HTML output.
- Tooltip pop-ups – Activated via
enable_tooltips=True, displaying node metadata and edge labels on hover. - Click callbacks – Custom inspection functions can be registered via
set_node_click_callback()to trigger Python-side logic when users select specific entities. - Control buttons – The implementation wires interactive physics controls through the
Network.show_buttonsAPI, allowing real-time adjustment of gravitational constants and spring lengths.
OntologyVisualizer Hierarchical Options
The OntologyVisualizer in semantica/visualization/ontology_visualizer.py specializes in rendering RDF schema and OWL ontologies. While it leverages the same PyVis backend as KGVisualizer, it adds preprocessing steps specifically designed for taxonomic structures.
Tree View Configuration
For hierarchical visualization, the class accepts a max_depth parameter that limits the expansion of rdfs:subClassOf chains. This prevents overwhelming the canvas with deep inheritance trees while preserving navigational context. The preprocessor builds a directed acyclic tree from RDF triples before passing the structure to the rendering engine.
Semantic Coloring and Relation Filtering
The visualizer provides ontology-specific styling options:
- Namespace-based coloring – The
paletteparameter (accepting values like"viridis") maps ontology namespaces or class types to distinct color schemes, making it easy to visually distinguish between imported vocabularies and local definitions. - Relation filtering – Developers can constrain displayed edges to specific predicates such as
rdf:typeorrdfs:subClassOf, hiding administrative or deprecated relations that clutter the hierarchy view. - Automatic legend generation – When
show_legend=True, the visualizer generates a color key mapping class types to their assigned palette values.
Export Capabilities and Shared API
Both visualizers implement a consistent interface for persistence and sharing:
display()– Renders an interactive HTML view inline in Jupyter notebooks or standalone browsers.save_html(filepath)– Exports a self-contained HTML file with embedded JavaScript, requiring no external dependencies for viewing.save_png(filepath)– Generates static raster snapshots suitable for documentation and publications.- SVG support – Vector exports are available through the underlying PyVis
Networkobject for lossless scaling in print media.
These methods are defined in the base visualization classes and shared across both knowledge graph and ontology implementations.
Practical Implementation Examples
The following examples demonstrate typical configuration patterns using the actual API surface from semantica/visualization/kg_visualizer.py and semantica/visualization/ontology_visualizer.py.
Basic Knowledge Graph with Spring Layout
from semantica.visualization.kg_visualizer import KGVisualizer
from semantica.graph import SemanticNetwork
g = SemanticNetwork.from_ttl("example_graph.ttl")
viz = KGVisualizer(
layout="spring",
node_style={"color": "lightblue", "shape": "dot"},
edge_style={"color": "gray", "arrows": "to"},
enable_tooltips=True
)
viz.display(g)
viz.save_png("knowledge_graph.png")
Ontology Hierarchy with Depth Limiting
from semantica.visualization.ontology_visualizer import OntologyVisualizer
from semantica.ontology import Ontology
onto = Ontology.from_rdf("my_ontology.ttl")
viz = OntologyVisualizer(
max_depth=3,
palette="viridis",
show_legend=True,
layout="hierarchical"
)
viz.display(onto)
viz.save_html("ontology_tree.html")
Custom Interaction Callbacks
def inspect_node(node_id):
metadata = g.get_node(node_id).metadata
print(f"Entity {node_id}: {metadata}")
viz = KGVisualizer(layout="circular", enable_tooltips=False)
viz.set_node_click_callback(inspect_node)
viz.display(g)
Summary
KGVisualizerinsemantica/visualization/kg_visualizer.pysupports spring, circular, and hierarchical layouts with full control over node shapes, colors, and edge arrowheads.OntologyVisualizerinsemantica/visualization/ontology_visualizer.pyadds tree-specific features includingmax_depthpruning, namespace-based semantic coloring, and relation filtering forrdfs:subClassOfhierarchies.- Both classes provide unified export methods (
display(),save_html(),save_png()) and leverage the PyVisNetworkobject for interactive web rendering. - Interactive capabilities include zoom, pan, tooltip inspection, and custom Python callbacks triggered by user clicks.
Frequently Asked Questions
What layout algorithms does KGVisualizer support?
KGVisualizer supports three layout algorithms selectable via the layout parameter: spring (force-directed), circular (radial arrangement), and hierarchical (directed tree/dot layout). These are applied when building the underlying pyvis.network.Network object in semantica/visualization/kg_visualizer.py.
How do I limit the depth of an ontology visualization?
Pass the max_depth integer parameter to OntologyVisualizer when initializing the class. This setting, processed in semantica/visualization/ontology_visualizer.py, truncates the rdfs:subClassOf hierarchy at the specified level, preventing deep inheritance chains from overwhelming the visual canvas while maintaining navigational context.
Can I export visualizations to static image formats?
Yes. Both visualizers implement the save_png() method for raster export and save_html() for self-contained interactive web pages. According to the implementation in semantica/visualization/kg_visualizer.py, these methods delegate to the PyVis Network object, which handles the underlying HTML5 Canvas rendering for PNG generation.
How do I add custom interactivity like click handlers?
Register a callback function using set_node_click_callback() on a KGVisualizer instance. This method wires your Python function to the JavaScript frontend, executing your logic whenever a user clicks a node in the interactive HTML view generated by the display() method.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →