Render your data in graphs with WebSharper
Sometimes we just want to show our data in a nicely rendered graph on our website. If we have enough data, everything could be done. Just think about it: Everyone loves graphs.
In WebSharper we have an extension for this: an F# API for Cytoscape.js. With Cytoscape creating and rendering graphs from your own data is easy and this combined with F#’s power is really useful tool!
To get Cytoscape in our project we just have to get it from NuGet under the name of
WebSharper.Cytoscape if you’re using WebSharper 3).
If we have our extension imported, we just have to open it with
open WebSharper.Cytoscape (both for WebSharper and Zafir). With this we are ready to use the extension and we are ready to show off our data in all kinds of fancy graphs.
An easy example
Just to show how it’s working I’m going to show you the original example graph from the Cytoscape website. We’re just going to create a simple WebSharper Single Page Application. Here’s a picture about the result we’ll get:
Let’s get started with the
index.html : We only need a container div somewhere in our
<body></body>. Let’s call this div “main”:
With this we’re done with the
index.html file. Let’s move on to our
To construct an object here, we’ll have to use some record types in F#. The extension already has those. Let’s see the constructor first, this uses the record called
let cy =
container is going to be really familiar to the original one (but we have a div with id “main”):
Container = JS.Document.GetElementById("main")
elements need another record type called
ElementObject(Data = ElementData(Id = "a"))
ElementObject(Data = ElementData(Id = "b"))
ElementObject(Data = ElementData(Id = "ab", Source = "a", Target = "b"))
ElementObject we construct the Data which is an
ElementData . Here everything has an
id , but the edges also have
style needs a record type as well:
selector = "node",
style = New [
"background-color" => "#666"
"label" => "data(id)"
selector = "edge",
style = New [
"width" => "3"
"line-color" => "#ccc"
"target-arrow-color" => "#ccc"
"target-arrow-shape" => "triangle"
style we don’t have an object, but we can create anonymous objects with
New ["label" => value;...] .
Only one thing’s left and that’s the
Layout . It is a simple record, we only want a grid layout with a single row:
Layout = LayoutOptions(
Name = "grid",
Rows = 1
Here’s the whole code:
With Cytoscape extension you’re able to do more complex graphs and even practice graph and set theory. I’ll post another story about those.
Be sure to leave a 💚, it helps me know what stories you want to read, and leave a comment if you have any question! Hope you had fun reading the post and found your love for F# and for WebSharper.