Combine layout algorithms

Apply FractalLayout and SpringLayout to generate a tag cloud

In a series of posts we’ll explore ways to combine graph layout algorithms for various purposes, such as improving layout speed or achieving specific layout constraints.

In this topic we’ll show how to create a tag cloud using FractalLayout and SpringLayout algorithms from MindFusion diagramming API. You can download the complete project here:

TagCloud.zip

The sample code will show several features of the Diagram control:

  • FractalLayout
  • SpringLayout
  • custom node placement
  • text-only nodes

We assume words frequencies are already counted and listed as “word: frequency” entries in a sorted file. The example uses tags extracted from the contents of Wikipedia’s Tag cloud page. Let’s start by parsing the file and creating a node for each word. We’ll assign the word frequency to the Weight property of nodes for future reference. Weight is also used by some layout algorithms (such as TreeMapLayout for creating tree maps) that could visually represent word frequencies as well:

RectangleF defaultBounds = new RectangleF(0, 0, 10, 20);
ShapeNode root;
		
private void MainForm_Load(object sender, EventArgs e)
{
	// read the tags file
	var reader = new StreamReader("words.txt");
	string line;
	while ((line = reader.ReadLine()) != null)
	{
		// each line contains "word: frequency" entries
		var parts = line.Split(new[] { ':' });
		var word = parts[0];
		var frequency = int.Parse(parts[1]);

		// create a diagram node for each word in the file
		var node = diagram.Factory.CreateShapeNode(defaultBounds);
		node.Weight = frequency;
		node.Text = word;

		// set font size corresponding to frequency
		node.Font = new Font(
			"Arial",
			8 + (float)Math.Log(node.Weight, 1.15),
			GraphicsUnit.Point);

		// resize the node to fit text
		var size = TextRenderer.MeasureText(node.Text, node.Font);
		node.Resize(
			2 + (float)MeasureUnit.Pixel.Convert(size.Width, diagram.MeasureUnit, null),
			2 + (float)MeasureUnit.Pixel.Convert(size.Height, diagram.MeasureUnit, null));

		// show only text, hide geometry
		node.Transparent = true;
	}
}

Next, let’s build a tree that will distribute largest nodes roughly uniformly when arranged by FractalLayout, where larger parent nodes are circled by their smaller child nodes:

while ((line = reader.ReadLine()) != null)
{
	// ...
	if (diagram.Nodes.Count == 1)
	{
		// save reference to the first node
		root = node;
	}
	else
	{
		// build a tree where each node has up to six children
		diagram.Factory.CreateDiagramLink(
			diagram.Nodes[diagram.Nodes.Count / 6],
			node);
	}
}

// use FractalLayout for initial placement. if the file entries are sorted, each circular
// branch will contain larger parent node centered between its smaller children
new FractalLayout().Arrange(diagram);

If you run the application now, you should see the following layout:

a tree arranged using fractal layout

FractalLayout allocates some space for links, and we’ll reclaim it by deleting the links and compressing the initial layout of nodes:

// remove the links
while (diagram.Links.Count > 0)
	diagram.Links.RemoveAt(diagram.Links.Count - 1);

// pull all nodes towards the root to eliminate empty space that was occupied by links
var center = root.GetCenter();
foreach (var node in diagram.Nodes.Where(n => n != root))
{
	var relativePos = new Vector(center, node.GetCenter());
	var newPos = center + relativePos / 10;
	node.Move(
		newPos.X - node.Bounds.Width / 2,
		newPos.Y - node.Bounds.Height / 2);
}

Now apply SpringLayout to make distances between closely placed nodes more uniform, running only a few iterations to complete faster:

// run SpringLayout to distribute nodes more uniformly
var sl = new SpringLayout();
sl.Randomize = false;
sl.SplitGraph = false;
sl.NodeDistance = 3;
sl.IterationCount = 40;
sl.Arrange(diagram);

Run the following method to remove any overlaps remaining after SpringLayout. RemoveOverlaps works by starting from specified node and offsetting any nodes that overlap it, continuing by spiraling away while processing other nodes. This method could also be useful in an interactive application if you want to disperse overlapping nodes introduced by the user when they move a node:

void RemoveOverlaps(DiagramNode modifiedNode, float minDist)
{
	var queue = new Queue();
	queue.Enqueue(modifiedNode);

	while (queue.Count > 0)
	{
		var node = queue.Dequeue();
		var nodeCenter = node.GetCenter();
		var overlaps = FindOverlaps(node, minDist);
		foreach (var overlap in overlaps)
		{
			var ovrCenter = overlap.GetCenter();
			var ovrBounds = overlap.Bounds;
			var dx = ovrCenter.X - nodeCenter.X;
			var dy = ovrCenter.Y - nodeCenter.Y;
			if (Math.Abs(dx) > Math.Abs(dy))
			{
				// offset horizontally
				if (dx < 0)
					ovrBounds.X = node.Bounds.Left - ovrBounds.Width - minDist;
				else
					ovrBounds.X = node.Bounds.Right + minDist;
			}
			else
			{
				// offset vertically
				if (dy < 0)
					ovrBounds.Y = node.Bounds.Top - ovrBounds.Height - minDist;
				else
					ovrBounds.Y = node.Bounds.Bottom + minDist;
			}

			// shifting the node might introduce new overlaps, continue processing
			overlap.Bounds = ovrBounds;
			queue.Enqueue(overlap);
		}
	}
}

List FindOverlaps(DiagramNode modifiedNode, float minDist)
{
	var bounds = modifiedNode.Bounds;
	bounds.Inflate(minDist - 1, minDist - 1);

	var overlaps = new List();
	foreach (var node in diagram.Nodes)
	{
		if (modifiedNode == node)
			continue;
		if (bounds.IntersectsWith(node.Bounds))
			overlaps.Add(node);
	}
	return overlaps;
} 

Finally run a few more iterations of SpringLayout to equalize distances again and zoom the diagram to show the whole tag cloud:

// remove any remaining overlaps
RemoveOverlaps(root, 0.1f);
sl.Arrange(diagram);

// show everything inside view
diagram.ResizeToFitItems(5);
diagramView.ZoomToFit();

If you run the application now, you should see the following image:

tag cloud generated using MindFusion diagram control

The code above uses MindFusion’s .NET API and can be used with Windows Forms, WPF, Silverlight and ASP.NET diagramming components. The Java API for Android and desktop Swing application will look similar, with setter method calls instead of property assignments.

You can download the trial version of any MindFusion.Diagramming component from this page.

Enjoy!

MindFusion.WebForms Pack, 2015.R1

MindFusion announceс а неш release of our WebForms suite of components. Here is an overview of the most important new features:

Licensing

We no longer make separate trial build of the control assemblies. Instead there is a new LicenseKey property, which disables a component’s evaluation mode. If your application contains more than one control by MindFusion, you could call MindFusion.Licensing.LicenseManager.AddLicense(key) to specify the key once instead of setting it per each control. License key strings are listed on the Keys & Downloads page at MindFusion’s customer portal.

Zoom control

The ZoomControl class from MindFusion.Common.WebForms lets users change interactively the current zoom level and scroll position of a DiagramView or a MapView. To set it up, add a ZoomControl element to the page and set the control’s TargetId property to the id of the view. The control has numerous properties for customizing its appearance.

ASP.NET Diagrammer: The Zoom control

ASP.NET Diagrammer: The Zoom control

Visual Studio 2015 Toolbox Support

MindFusion.WebForms components can now be installed automatically into Visual Studio 2015 toolbox palette.

chartMindFusion.Charting

Custom Formatting of Labels for Line charts

Line charts now support custom formatting of labels. To use custom formatting, set LabelFormat to NumberFormat.Custom and use LabelCustomFormat.

Sorted Bars

The algorithm for sorting of bars has been improved. Bars in a series or in clusters can be sorted in ascending or descending order – use the SortOrder property. You can also sort each series/cluster with the SortSeriesBy property. Bar can be sorted with their colors preserved if SortColor is set to true.

ASP.NET Chart: The Bar chart control

ASP.NET Chart: The Bar chart control

MindFusion WebForms DiagrammerMindFusion.Diagramming

Canvas mode improvements

  • Shape property of TableNode and ContainerNode is now supported in Canvas mode.
  • CellFrameStyle and EnableStyledText properties of TableNode are now supported in Canvas mode.
  • CellTextEditedScript event raised when users edit the text of table cells.
  • CreateEditControlScript event lets you create custom DOM element or fragment to use as in-place text editor.
  • NodeListView raises nodeSelected event when the user selects a node.
  • Load XML files from client side by calling loadFromXml method of Diagram class.
  • as well many more new properties and events.

Styled text in Canvas mode

The EnableStyledText property of ShapeNode allows using HTML-like formatting tags to apply various attributes to the node’s text. At this time the component supports the following formatting tags:

<b> specifies bold text
<i> specifies italic text
<u> specifies underlined text
<color=value> specifies text color
<br /> specifies line break

Zoom control

(not available in JavaApplet mode)
The ZoomControl class lets users change interactively the current zoom level and scroll position of a DiagramView. To set it up, add a ZoomControl element to the page and set the control’s TargetId property to the id of a DiagramView. The control offers numerous customization properties like ZoomStep, ScrollStep and various appearance setting properties such as Fill, BorderColor, CornerRadius and TickPosition.

WebForms Gauge Control by MindFusionMindFusion.Gauges

Linear and oval gauge controls have been added to MindFusion.WebForms pack. The gauges are drawn on client side using HTML Canvas API. Users can change gauge values interactively by dragging their elements.

The ASP.NET Gauge control

The ASP.NET Gauge control

WebForms Scheduler by MindFusionMindFusion.Scheduling

Horizontal Timetable view

Horizontal layout has been added to the Timetable view. The horizontal timetable view displays a collection of rows where each row represents the allotment of resources to distinct hours of a day; the rows in this view represent dates, tasks, locations, contacts or resources.

ASP.NET UI Suite of controlsMindFusion.UI

The bundled jQuery version has been upgraded to 1.11.2.

You can read further details about the release at the announcement page at MindFUsion discussion board.

The trial version of the new MindFusion.WebForms Pack is available for direct download from this link:

Download MindFusion ASP.NET Pack 2015.R1

About MindFusion.WebForms Pack: A set of WebForms components that add great variety of features to your ASP.NET application with a few mouse clicks. The pack contains advanced components for diagramming, scheduling, charting and UI (Accordion, ColorPicker, TabControl, Window, WindowHost, DockControl, Button, Slideshow, Zoom and more). Each tool boasts easy to learn and use API and is quickly integrated into any web application that targets the ASP.NET platform. The controls support numerous options for styling, data import / export, user interaction and offer rich event set. There are plenty of samples and step-by-step tutorials as well detailed documentation.

Use the features page for each of the tools to find out more about its capabilities and the numerous ways it can boost your performance and speed up the development of your application:

Visit the buy page for details on the licensing scheme and prices. If you have questions please contact us. We shall be happy to assist you.

Diagramming for ASP.NET, V5.4.2

The new version 5.4.2 of Diagramming for ASP.NET offers web developers a setoff useful new features. Here are the details:

Canvas mode improvements

  • Shape property of TableNode and ContainerNode is now supported in Canvas mode.
  • CellFrameStyle and EnableStyledText properties of TableNode are now supported in Canvas mode.
  • CellTextEditedScript event raised when users edit the text of table cells.
  • CreateEditControlScript event lets you create custom DOM element or fragment to use as in-place text editor.
  • NodeListView raises nodeSelected event when the user selects a node.
  • Load XML files from client side by calling loadFromXml method of Diagram class.
  • Fixed setZoomFactorPivot bug in virtual scroll mode.
MindFusion ASP.NET Diagram Control: Table Nodes

MindFusion ASP.NET Diagram Control: Table Nodes

Miscellaneous

  • NodeTextEdited, LinkTextEdited and CellTextEdited server-side events.
  • createThickness method added to ScriptHelper.
  • Sample projects have been improved and extended.
MindFusion ASP.NET Diagram Control: Container Nodes

MindFusion ASP.NET Diagram Control: Container Nodes

Here is a direct link to download the trial version:

Download MindFusion.Diagramming for ASP.NET, V5.4.2 Trial Version

Technical support
MindFusion support team is happy to assist you with any questions you might have about Diagramming for ASP.NET or any other of our products. You can leave a message at the discussion board, use the help desk or e-mail support@mindfusion.eu.. We strive to provide competent and detailed answers to your questions within hours of receiving them.

About Diagramming for ASP.NET: An advanced WebForms programming component that offers all the functionality that is needed for creating, styling and presenting attractive flowcharts, hierarchies, trees, graphs, schemes, diagrams and many more. The control offers numerous utility methods, path finding and cycle detection, rich event set and many useful user interaction features like tool tips, multiple selection, copy/paste to/from Windows clipboard and many more.

NetDiagram offers more than 100 predefined node shapes, scrollable tables, 13 automatic layouts and many
more. You can check the online demo to see some of the features in action. The control includes many samples, detailed documentation and step-by-step tutorials. Every features is duly documented and there’s plenty of code to copy. The component is not only powerful and scalable, but easy to learn and fun to use.

Diagramming for ActiveX V4.9.1 Released!

MindFusion is proud to announce the new release of its ActiveX Diagramming control. Here is an overview of the new features:

Highlight table rows
You can use the new HighlightedRow property of a Table to the index of a row that should be drawn highlighted. You can set the background of highlighted rows’ with RowHighlightColor. With the new AutoHighlightRows property, a row will be highlighted automatically when clicked.

Tables in the diagramming for ActiveX component.

Tables in the diagramming for ActiveX component.

Miscellaneous

  • VisioImporter, VisioExporter and SvgExporter has been merged into the main flowchartx.dll library file, and can now be used with its 64-bit version.
  • Set the BackColor property of ArrowLabel to fill the background of link labels.
  • Link segments now connect to the base of arrowhead shapes instead of going all the way through them, letting you use transparent and semi-transparent fill color for arrowheads without seeing segment ends inside.
  • Fixed crash in 64-bit SaveToBitmap function.

The trial version of the control is available for download from here:

Download FlowChartX 4.9.1 Trial Version

Technical support
MindFusion puts special effort in providing excellent customer support to all developers who use our components. You can write at the forum, help desk or use e-mail support@mindfusion.eu. All questions are usually answered within hours of being received.

About MindFusion.Diagramming for ActiveX: An ActiveX programming component that lets you create with ease every type of diagram, flowchart, scheme, chart, hierarchy, tree etc. The control supports rich user interaction model with advanced features like tool tips, grid alignment, docking points for nodes, scrolling and zooming and many more. FlowChartX implements 7 automatic layouts as well arrow routing. The appearance if each flowchart is completely customizable. Nodes can hold both images and text, their Z-order can be changed and there are tens of predefined shapes to choose from. Nodes support aero and glass visual effects.

The control also includes detailed documentation and many samples for a variety of languages and
platforms. You can find more about the features of the tool at the features page or check the licensing scheme and the prices here.

Diagramming for ASP.NET MVC, V2.5

MindFusion is pleased to announce the new release of Diagramming for ASP.NET MVC. It includes:

Appearance improvements

  • You can use the new Shape property of tables and containers to RoundedRectangle to render them with rounded corners.
  • Now it is possible to hide the frames of table cells by setting the CellFrameStyle property to None.
  • You can set the EnableStyledText property of TableNode class to render styled text in tables.
ASP.NET MVC Diagram Control:  Container Nodes

ASP.NET MVC Diagram Control: Container Nodes

New events

  • The control raises cellTextEdited event when users edit the text of table cells.
  • The createEditControl event lets you create custom DOM element or fragment to use as in-place text editor.
  • NodeListView raises nodeSelected event when the user selects a node.

Miscellaneous

  • Width and Height properties and the corresponding setter methods for DiagramView, NodeListView, Overview and ZoomControl are now obsolete. You can use new helper methods of the controls to pass an HTML attributes object, containing dimensions and other style data.
  • You can now prevent the control from automatically adding references to script files by disabling the AddScriptReferences property.
  • The loadFromXml(url) method of Diagram class lets you load XML files from client side.
  • We have fixed a setZoomFactorPivot bug in virtual scroll mode.

The trial version is available for direct download from the link below:

Download MindFusion.Diagramming for ASP.NET MVC, V2.5

MindFusion support team is happy to assist you with any questions you might have about Diagramming for ASP.NET MVC or any other of our products. You can leave a message at the discussion board, use the help desk or e-mail support@mindfusion.eu.. We strive to provide competent and detailed answers to your questions within hours of receiving them.

About Diagramming for ASP.NET MVC Control: It is a multi-purpose diagramming tool that consists of two parts: a .NET class library running on the server and a client side control implemented in JavaScript. The server side .NET library implements a flow-diagramming object model that lets you define structures such as trees, flowcharts and graphs. Every element in the diagram is easily accessible and the whole diagram is rendered as part of an HTML page by just calling the DiagramView extension method.

On the client the diagram is rendered by a DiagramView JavaScript control that draws its content on an HTML Canvas. The user is able to add nodes and links simply by drawing them with the mouse. There is also a NodeListView control, which lets users create new nodes via drag and drop.

MvcDiagram also supports various automatic layout algorithms that will make every diagram easy to understand and nice to look at. The diagram can also be easily serialized in binary or XML format. Exporting is done in a variety of formats including Pdf, Svg, Visio and more. You can read details about the components at the MvcDiagram features page.