How to Visualize the Knowledge Graph Generated by Semantica: Complete Developer Guide
Semantica's KGVisualizer class converts internal KnowledgeGraph objects into interactive network diagrams, community colorings, and statistical charts through a standardized 10-step pipeline orchestrated in kg_visualizer.py.
The semantica-agi/semantica repository ships with a comprehensive visualization subsystem that transforms abstract knowledge representations into explorable visual formats. Whether you need to inspect entity relationships, analyze community structures, or export publication-ready figures, the toolkit supports multiple output formats including interactive HTML, static PNG, and inline notebook displays.
KGVisualizer Architecture and Core Pipeline
The visualization workflow centers on the KGVisualizer class defined in [semantica/visualization/kg_visualizer.py](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/kg_visualizer.py). This orchestrator accepts any dictionary-compatible graph structure containing "entities" and "relationships" keys, making it compatible with native KnowledgeGraph instances, GraphBuilder outputs, or custom extraction pipelines.
When you invoke any visualization method, the engine executes a deterministic 10-step pipeline:
-
Dependency Verification – The
_check_dependenciesmethod validates Plotly availability before rendering. -
Graph Normalization – Internal
KnowledgeGraphobjects are converted to plain dictionaries via_convert_knowledge_graphand_normalize_graph, ensuring consistent schema access. -
Node and Edge Extraction – Helper methods
_extract_nodesand_extract_edgesretrieve identifiers, labels, types, and metadata fields required for rendering. -
Layout Computation – Based on the
layoutparameter (force,hierarchical, orcircular), the system delegates to algorithms in [layout_algorithms.py](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/utils/layout_algorithms.py) to generate(x, y)coordinates. -
Color Mapping – Node colors resolve from explicit
colorfields or dynamic property mapping (node_color_by) using palettes defined in [color_schemes.py](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/utils/color_schemes.py) viaColorPalette.get_entity_type_colorsorColorPalette.get_community_colors. -
Size Scaling – When
node_size_byis specified, values normalize to a 10–50 pixel range; otherwise staticnode_sizeapplies. Centrality visualizations inject computed scores viavisualize_centrality. -
Hover Data Enrichment – The engine constructs HTML hover strings combining node labels, types, and additional fields specified in
hover_data. -
Path Highlighting – Optional
highlight_patharguments triggerclassify_path_distance(from [semantica/utils/helpers.py](https://github.com/semantica-agi/semantica/blob/main/semantica/utils/helpers.py)) to style edges by hop distance. -
Figure Assembly – Plotly
Scattertraces are constructed for background edges, highlighted paths, edge labels, and nodes, with automatic annotation handling for small graphs. -
Export or Return – If
file_pathis provided, [export_formats.py](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/utils/export_formats.py) handles serialization viaexport_plotly_figureorexport_matplotlib_figure; otherwise the interactive object returns for immediate display.
Visualizing Network Topology
The most common use case renders the complete entity-relationship structure as an interactive network diagram.
from semantica.visualization import KGVisualizer
# Initialize with force-directed layout and vibrant color scheme
viz = KGVisualizer(layout="force", color_scheme="vibrant")
# Generate interactive visualization
fig = viz.visualize_network(
graph, # KnowledgeGraph instance or compatible dict
output="interactive",
node_color_by="type",
hover_data=["metadata", "confidence"],
)
fig.show()
This method leverages the full pipeline, automatically selecting layout algorithms from ForceDirectedLayout, HierarchicalLayout, or CircularLayout based on your configuration.
Highlighting Communities and Clusters
When analyzing graph topology, community assignments require distinct visual encoding. The visualize_communities method accepts pre-computed partition dictionaries and maps them to discrete color palettes.
communities = {
"node_assignments": {"n1": 0, "n2": 1, "n3": 0},
"num_communities": 2,
}
viz.visualize_communities(
graph,
communities,
output="html",
file_path="communities.html",
)
The system invokes ColorPalette.get_community_colors to assign distinct hues to each detected community, ensuring visual separation between clusters.
Centrality-Driven Analysis
To emphasize structural importance, pass centrality scores to scale node sizes proportionally.
centrality_data = {
"centrality": {"n1": 0.7, "n2": 0.2, "n3": 0.5},
}
viz.visualize_centrality(
graph,
centrality_data,
centrality_type="degree",
output="png",
file_path="centrality.png",
)
The visualize_centrality method injects normalized size values into the rendering pipeline, overriding static node_size parameters with centrality-weighted scaling within the 10–50 pixel range.
Statistical Visualizations
Beyond network diagrams, the toolkit generates aggregate statistical charts.
Entity Type Distribution:
fig = viz.visualize_entity_types(
graph,
output="interactive",
)
fig.show()
Relationship Frequency Heatmaps:
fig = viz.visualize_relationship_matrix(
graph,
output="interactive",
)
fig.show()
These methods bypass layout algorithms and instead utilize Plotly's native chart types to reveal dataset composition patterns.
Configuration and Export Options
The visualization subsystem supports flexible output targets through export_formats.py. Specify output="html" for standalone interactive files, output="png" for static raster images, or output="interactive" for Jupyter notebook embedding.
Key configuration parameters include:
layout: Selects the positioning algorithm (force,hierarchical,circular)color_scheme: References palettes defined incolor_schemes.pynode_color_by: Maps visual encoding to entity properties or community IDshighlight_path: Accepts node sequences for path tracing with distance-based edge styling
Summary
- The
KGVisualizerclass inkg_visualizer.pyserves as the central orchestrator for all Semantica knowledge graph visualization tasks. - A standardized 10-step pipeline handles normalization, layout calculation via
layout_algorithms.py, color mapping throughcolor_schemes.py, and multi-format export. - Five primary visualization modes support network topology, community detection, centrality analysis, entity distributions, and relationship matrices.
- The system accepts any dictionary-compatible graph with
"entities"and"relationships"keys, ensuring flexibility acrossKnowledgeGraphinstances and custom data structures. - Export options include interactive HTML, static PNG, and inline notebook rendering via
export_plotly_figureandexport_matplotlib_figure.
Frequently Asked Questions
Can I visualize a custom graph not created by Semantica's KnowledgeGraph builder?
Yes. The KGVisualizer operates on plain dictionaries containing "entities" and "relationships" keys. As long as your custom graph adheres to this schema, the _convert_knowledge_graph and _normalize_graph methods will process it without requiring native KnowledgeGraph instantiation.
Which layout algorithm performs best for large knowledge graphs with thousands of nodes?
The force layout (force-directed) generally produces the most interpretable results for complex, highly-connected graphs, though computation time increases with node count. For hierarchical taxonomies, use hierarchical from layout_algorithms.py to leverage directed structure and minimize edge crossings.
How do I customize the color palette for entity types?
Pass a custom mapping or reference alternative schemes via the color_scheme parameter during KGVisualizer initialization. The ColorPalette class in color_schemes.py exposes get_entity_type_colors for programmatic palette generation, allowing you to override default hues or define domain-specific color mappings.
Is it possible to export visualizations programmatically without displaying them?
Absolutely. Specify a file_path argument in any visualize_* method combined with output="html" or output="png". The system routes to export_plotly_figure or export_matplotlib_figure in export_formats.py, writing directly to disk and suppressing interactive display.
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 →