Graph visualization with rust, petgraph and egui in its DNA.
The project implements a Widget for the egui framework, enabling easy visualization of interactive graphs in rust. The goal is to implement the very basic engine for graph visualization within egui, which can be easily extended and customized for your needs.
The project is on track for a stable release v1.0.0. For the moment, breaking releases are still possible.
Docs can be found here
First, let's define the BasicApp
struct that will hold the graph.
rust
pub struct BasicApp {
g: Graph<(), (), Directed>,
}
Next, implement the new()
function for the BasicApp
struct.
rust
impl BasicApp {
fn new(_: &CreationContext<'_>) -> Self {
let g = generate_graph();
Self { g: Graph::from(&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.
```rust
fn generate_graph() -> StableGraph<(), (), Directed> {
let mut g: StableGraph<(), ()> = StableGraph::new();
let a = g.add_node(());
let b = g.add_node(());
let c = g.add_node(());
g.add_edge(a, b, ());
g.add_edge(b, c, ());
g.add_edge(c, a, ());
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.
rust
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
.
rust
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.