Graph visualization with rust, petgraph and egui in its DNA.
This project represents a Widget
implementation for egui framework. It allows effortless interactive graph visualization with rust.
- Node folding;
- Layouts;
- Arbitrarily complex graphs with self-references, multiple edges, loops, etc.;
- Zoom & pan;
- Dragging, Selecting;
- Graph elements style configuration;
- Support for egui dark/light mode;
- Selection depth;
- Changes reporting;
The project is on the track to v1.0.0 and there will be some minor releases prior. So stay tuned!
First, let's define the BasicApp
struct that will hold the graph.
pub struct BasicApp {
g: StableGraph<Node<()>, Edge<()>>,
}
Next, implement the new()
function for the BasicApp
struct.
impl BasicApp {
fn new(_: &CreationContext<'_>) -> Self {
let g = generate_graph();
Self { g }
}
}
Create a helper function called generate_graph()
. In this example, we create three nodes with and three edges connecting them in a triangular pattern.
fn generate_graph() -> StableGraph<Node<()>, Edge<()>> {
let mut g: StableGraph<Node<()>, Edge<()>> = StableGraph::new();
let a = g.add_node(Node::new(egui::Vec2::new(0., SIDE_SIZE), ()));
let b = g.add_node(Node::new(egui::Vec2::new(-SIDE_SIZE, 0.), ()));
let c = g.add_node(Node::new(egui::Vec2::new(SIDE_SIZE, 0.), ()));
g.add_edge(a, b, Edge::new(()));
g.add_edge(b, c, Edge::new(()));
g.add_edge(c, a, Edge::new(()));
g
}
Now, lets implement the update()
function for the BasicApp
. This function creates a GraphView
widget providing a mutable reference to the graph, and adds it to egui::CentralPanel
using the ui.add()
function for adding widgets.
impl App for BasicApp {
fn update(&mut self, ctx: &Context, _: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.add(&mut GraphView::new(&mut self.g));
});
}
}
Finally, run the application using the run_native()
function with the specified native options and the BasicApp
.
fn main() {
let native_options = eframe::NativeOptions::default();
run_native(
"egui_graphs_basic_demo",
native_options,
Box::new(|cc| Box::new(BasicApp::new(cc))),
)
.unwrap();
}
You can further customize the appearance and behavior of your graph by modifying the settings or adding more nodes and edges as needed.
It is easy to add interactivity to the visualization. Just use SettingsNavigation
and SettingsInteraction
with constructor methods. You can also check interactive demo and comprehensive configurable demo for usage references and settings description.