# How to Visualize Knowledge Graphs and Ontology Hierarchies in Semantica

> Visualize knowledge graphs and ontology hierarchies easily with Semantica's OntologyVisualizer and KGVisualizer. Create interactive Plotly figures or static Graphviz exports with customizable options.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: how-to-guide
- Published: 2026-08-14

---

**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`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/ontology_visualizer.py) and [`semantica/visualization/kg_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/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:

```python
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"`:

```python
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`](https://github.com/semantica-agi/semantica/blob/main/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()`:

```python
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`](https://github.com/semantica-agi/semantica/blob/main/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()`:

```python
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`](https://github.com/semantica-agi/semantica/blob/main/utils/helpers.py) to apply distance-aware styling:

```python
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`](https://github.com/semantica-agi/semantica/blob/main/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 unknown
- **`HierarchicalLayout`** — Optimal for tree-like or layered ontologies with clear directionality
- **`CircularLayout`** — Useful for comparing node attributes around a central axis

### Export Formats

The [`utils/export_formats.py`](https://github.com/semantica-agi/semantica/blob/main/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`](https://github.com/semantica-agi/semantica/blob/main/semantica/utils/progress_tracker.py). This enables:

- Structured logging during long-running visualizations
- Status reporting for CLI commands defined in [`semantica/worker.py`](https://github.com/semantica-agi/semantica/blob/main/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

- **`OntologyVisualizer`** in [`semantica/visualization/ontology_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/ontology_visualizer.py) renders class hierarchies, property graphs, and metrics dashboards with both Plotly interactivity and Graphviz static export
- **`KGVisualizer`** in [`semantica/visualization/kg_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/kg_visualizer.py) handles knowledge graph networks with support for community detection, centrality overlays, and path highlighting
- **Layout algorithms** (`ForceDirectedLayout`, `HierarchicalLayout`, `CircularLayout`) live in [`semantica/visualization/utils/layout_algorithms.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/utils/layout_algorithms.py) and are selected via the `layout` parameter
- **Color schemes** from [`utils/color_schemes.py`](https://github.com/semantica-agi/semantica/blob/main/utils/color_schemes.py) provide consistent, accessible styling across all visualizations
- **Export flexibility** via [`utils/export_formats.py`](https://github.com/semantica-agi/semantica/blob/main/utils/export_formats.py) supports 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`](https://github.com/semantica-agi/semantica/blob/main/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.