How to Visualize Knowledge Graphs and Ontology Hierarchies in Semantica
Semantica provides dedicated OntologyVisualizer and KGVisualizer classes that transform ontologies and knowledge graphs into interactive Plotly figures or static Graphviz exports with customizable layouts, color schemes, and metrics overlays.
The semantica-agi/semantica repository ships a comprehensive visualization package that bridges the gap between raw semantic data and interpretable visual representations. Whether you need to explore class hierarchies in an ontology or navigate complex entity-relationship networks in a knowledge graph, the library offers authoritative, production-ready tools with minimal configuration overhead.
Core Visualization Classes
Semantica's visualization architecture centers on two specialized classes defined in semantica/visualization/ontology_visualizer.py and semantica/visualization/kg_visualizer.py:
| Visualizer | Primary Output | Best For |
|---|---|---|
OntologyVisualizer |
Class trees, property graphs, metrics dashboards, DOT exports | Taxonomy exploration, schema documentation |
KGVisualizer |
Network graphs, community visualizations, centrality overlays | Entity relationship analysis, path investigation |
Both classes share a unified six-stage pipeline: dependency checking, input normalization, data analysis, layout computation, styling application, and interactive rendering.
Visualizing Ontology Hierarchies
The OntologyVisualizer class specializes in rendering class-property structures with multiple representation modes.
Basic Hierarchy Visualization
The visualize_hierarchy() method builds parent-child trees via _build_hierarchy_tree() and routes to either Plotly or Graphviz rendering based on the output parameter:
from semantica.visualization import OntologyVisualizer
viz = OntologyVisualizer(color_scheme="default", node_size=20)
fig = viz.visualize_hierarchy(
ontology=my_ontology, # dict, SemanticNetwork, or OntologyGenerator output
output="interactive", # or "dot" for Graphviz
node_color_by="level", # color by hierarchy depth
node_size_by="instances", # size by instance count
hover_data=["description"], # extra tooltip fields
)
fig.show()
Static Export with Graphviz
For publication-quality static assets, trigger the Graphviz path by setting output="dot":
viz.visualize_hierarchy(
ontology=my_ontology,
output="dot",
file_path="ontology_hierarchy.svg",
)
This delegates to _visualize_hierarchy_graphviz() in the source and requires Graphviz system installation.
Visualizing Knowledge Graph Networks
The KGVisualizer class in semantica/visualization/kg_visualizer.py handles entity-relationship networks with advanced analytical overlays.
Network Layout with Normalized Input
The class accepts multiple input formats through _normalize_graph():
from semantica.visualization import KGVisualizer
kg_viz = KGVisualizer(
layout="force", # alternatives: "hierarchical", "circular"
color_scheme="vibrant",
node_size=10
)
fig = kg_viz.visualize_network(
graph=kg, # KnowledgeGraph object or dict with "entities"/"relationships"
output="interactive",
node_color_by="type",
hover_data=["name", "type"],
)
fig.show()
Layout algorithms are imported from semantica/visualization/utils/layout_algorithms.py, which provides HierarchicalLayout, ForceDirectedLayout, and CircularLayout.
Centrality-Based Visualization
Highlight influential nodes by pre-computing centrality scores and passing them to visualize_centrality():
centrality = {
"centrality": {"E1": 0.42, "E2": 0.87, "E3": 0.15}
}
fig = kg_viz.visualize_centrality(
graph=kg,
centrality=centrality,
centrality_type="degree", # or "betweenness", "closeness", "eigenvector"
output="interactive",
node_color_by="type",
hover_data=["name", "type"],
)
Path Highlighting for Investigation
Use highlight_path to emphasize specific traversals through the network. The method leverages classify_path_distance from utils/helpers.py to apply distance-aware styling:
path = ["Person:Alice", "WorksAt:CompanyX", "LocatedIn:CityY"]
fig = kg_viz.visualize_network(
graph=kg,
output="interactive",
highlight_path=path, # ordered list of node IDs
node_color_by="type",
)
Non-path edges receive reduced opacity and width based on their distance from the highlighted trail.
Customization and Styling
Color Schemes
Palettes are managed through semantica/visualization/utils/color_schemes.py, which defines ColorScheme enumerations. Available schemes include "default", "vibrant", "pastel", and "monochrome".
Layout Algorithms
Select from three layout strategies based on graph topology and analytical goals:
ForceDirectedLayout— Best for free-form networks where community structure is unknownHierarchicalLayout— Optimal for tree-like or layered ontologies with clear directionalityCircularLayout— Useful for comparing node attributes around a central axis
Export Formats
The utils/export_formats.py module standardizes output across formats:
| Format | Use Case | Method |
|---|---|---|
| HTML | Interactive web embedding | fig.write_html() |
| PNG/SVG | Static publication figures | Matplotlib/Plotly renderers |
| DOT | Graphviz-compatible diagrams | Native _visualize_*_graphviz() methods |
Integration with Pipelines
Both visualizers integrate with Semantica's progress tracking system via get_progress_tracker() from semantica/utils/progress_tracker.py. This enables:
- Structured logging during long-running visualizations
- Status reporting for CLI commands defined in
semantica/worker.py - Deterministic progress bars for batch operations
Dependencies and Prerequisites
| Dependency | Required For | Check Location |
|---|---|---|
| Plotly | All interactive output | _check_dependencies() in each visualizer class |
| Graphviz | DOT export functionality | Optional; runtime detection |
| NetworkX | Centrality calculations | Typically pre-computed externally |
The _check_dependencies() method runs automatically on instantiation and raises informative errors if required packages are absent.
Summary
OntologyVisualizerinsemantica/visualization/ontology_visualizer.pyrenders class hierarchies, property graphs, and metrics dashboards with both Plotly interactivity and Graphviz static exportKGVisualizerinsemantica/visualization/kg_visualizer.pyhandles knowledge graph networks with support for community detection, centrality overlays, and path highlighting- Layout algorithms (
ForceDirectedLayout,HierarchicalLayout,CircularLayout) live insemantica/visualization/utils/layout_algorithms.pyand are selected via thelayoutparameter - Color schemes from
utils/color_schemes.pyprovide consistent, accessible styling across all visualizations - Export flexibility via
utils/export_formats.pysupports HTML, PNG, SVG, and Graphviz DOT formats for diverse consumption contexts
Frequently Asked Questions
What input formats do the visualizers accept?
OntologyVisualizer and KGVisualizer both accept plain Python dictionaries, SemanticNetwork instances, or concrete KnowledgeGraph objects. The KGVisualizer._normalize_graph() method standardizes these inputs before processing, while OntologyVisualizer handles flexible ontology representations directly.
Can I visualize knowledge graphs without installing Graphviz?
Yes. Graphviz is optional and only required for DOT export. All interactive Plotly output functions without any system dependencies beyond Python packages. The _check_dependencies() method verifies availability at runtime and gracefully degrades when Graphviz is absent.
How do I choose between layout algorithms?
Select based on your graph structure: force for unstructured networks with unknown topology, hierarchical for tree-like ontologies or directed acyclic graphs, and circular for cyclic comparisons or radial attribute analysis. The layout parameter accepts these as lowercase strings in the KGVisualizer constructor or method calls.
Is path highlighting available for ontologies?
Path highlighting is currently implemented only in KGVisualizer via the highlight_path parameter, which uses classify_path_distance from utils/helpers.py. For ontology hierarchies, use node_color_by="level" to visually distinguish depth layers, or export to DOT for manual path annotation in Graphviz.
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 →