d3.js with Dynamic Data II

A slightly adopted version using SVG. A form to control radius of randomly drawn circles.

<!DOCTYPE html>
<html>
    <head>
        <title>Hello, data!</title>
        <script type="text/javascript" src="lib/d3.js"></script>
    </head>
    <body>

        <form name="myform" onSubmit="return handleClick()">
            <input name="Submit"  type="submit" value="Radius" />
            <input type="text" id="myRadius"/>
        </form>

        <div id="viz"></div>

        <script type="text/javascript">

            var mySVG = d3.select("#viz")
            .append("svg:svg")
            .attr("width", 600)
            .attr("height", 400);

            function handleClick(event){
                console.log(document.getElementById("myRadius").value)
                draw(document.getElementById("myRadius").value)
                return false;
            }

            function draw(rad){
                mySVG.append("svg:circle")
                .style("stroke", "black")
                .style("fill", "grey")
                .attr("r", rad)
                .attr("cx", Math.round(Math.random()*600))
                .attr("cy", Math.round(Math.random()*400))
            }

        </script>
    </body>
</html>

SVG circles

Advertisements

d3.js with Dynamic Data

On the journey to learn d3.js it is most important to understand the basic principles first, but once you got your hands dirty, thanks to lots of samples, you want make data ‘speak’. The available samples refer to static data sitting in variables or coming from a json or csv files, sooner or later you want to feed data dynamic into your visualization. In this very simple sample we want values from a form sitting on the same html page to be added to a list, as simple as no svg involved.

<!DOCTYPE html>
<html>
    <head>
        <title>Hello, data!</title>
        <script type="text/javascript" src="lib/d3.js"></script>
    </head>
    <body>
        <form name="myform" onSubmit="return handleClick()">
            <input name="Submit"  type="submit" value="Add Value" />
            <input type="text" id="myVal"/>
        </form>

        <p></p>
        <p></p>
        <p></p>
        <p></p>
        <p></p>

        <script type="text/javascript">

            var dataset = [];
            for(i=0; i<5; i++){
                dataset.push(Math.round(Math.random()*50));
            }

            var p = d3.select("body").selectAll("p")
            .data(dataset)
            .text(function(d,i){return i + " : " + d;});

            function handleClick(event){
                console.log(document.getElementById("myVal").value)
                draw(document.getElementById("myVal").value)
                return false;
            }

            function draw(val){
                d3.select("body").append("p");
                dataset.push(val);
                var p = d3.select("body").selectAll("p")
                .data(dataset)
                .text(function(d,i){return i + " : " + d;})
            }

        </script>

    </body>
</html>

Dynamic Data

In the next step we will play with some svg, from there I will explore ZK feeding a visualization from a DB or any other feed.

ZK and the clipboard

 

Sounds too simple and it is present at a lot of websites: Copy to clipboard
I never had the requirement to copy text from a website to the clipboard, like you get the git URL when you are on a GIT project website and click the little icon. Same if you hover over the sourcecode below, you will get a copy option.

github.com

No, it is not possible to use simple javascript because it cant access your clipboard and you have no other chance then using one of the flash movie based solutions, like zeroclipboard, maybe one of the most popular ones.
The usual question: How do I get this embeded into my ZK web application ?

Short Tutorial:

  • Download the latest tar from code.google.com
  • Download the latest jQuery from jquery.com
  • Create a simple ZK web application
  • Place the jquery and zeroclipboard files into your Web Pagesfolder

    required files

  • Modify the index.zul file
    <?xml version="1.0" encoding="UTF-8"?>
    <zk xmlns="http://www.zkoss.org/2005/zul">
    
        <window id="info" apply="controller.indexController">
           <script src="jquery-1.6.4.js" type="text/javascript" />
           <script type="text/javascript" src="ZeroClipboard.js"/>
    
            <div id="d_clip_container">
                <image src="/Clipboard.png" />
            </div>
    
            <textbox id= "txtClipText"   cols="50" readonly="true" value="Some string for the clipboard"/>
    
            <script>
    		var clip = null;
    
    		function $(id) { return document.getElementById(id); }
    
                    function init(divId,clipText) {
                        ZeroClipboard.setMoviePath("ZeroClipboard.swf");
                        var clip = new ZeroClipboard.Client();
    
                        clip.addEventListener('mouseOver', function (client) {
                            clip.setText(zk.Widget.$(jq("$txtClipText")).getValue() );
                            //clip.setText(clipText);
                        });
    
                        clip.addEventListener('complete', function (client, text) {
                            alert("Copied text to clipboard: \n\n" + text );
                        });
    
                        clip.glue(divId);
    		}
            </script>
            <textbox value="" cols="30"/>
        </window>
    </zk>
    

    Remarks:

    • Using clip.setText(zk.Widget.$(jq(“$txtClipText”)).getValue() ); you can access a ZK textbox on the same page
    • With clip.setText(clipText); you can pass a text from the controller
  • Create a controller class
    package controller;
    
    import org.zkoss.zk.ui.Component;
    import org.zkoss.zk.ui.util.Clients;
    import org.zkoss.zk.ui.util.GenericForwardComposer;
    import org.zkoss.zul.Div;
    import org.zkoss.zul.Image;
    
    public class indexController extends GenericForwardComposer {
    
        Div d_clip_container;
        Image imgClipboard;
    
        @Override
        public void doAfterCompose(Component comp) throws Exception {
            super.doAfterCompose(comp);
    
            String command = "init('" + d_clip_container.getUuid() + "','some Text from controller');";
            Clients.evalJavaScript(command);
    
        }
    
    }
    
  • Run the application

    Running web application

 

Remarks:

  • Thanks to my team to get this running 🙂
  • Most of it we learned by tinkering with the sample code from zeroclipboard.
  • I dont favor Flash solutions because we depend on Adobe’s policies and changes. While Flash 9 allow reading and writing the clipboard easily, they consider it as a security risk in Flash 10. And only the trickery above makes it work. We wont know what Adobe will do in future versions, the above solution might break.

d3.js Tree: most simple sample

Learning d3.js might not be as easy as some other tools because there are no step-by-step instructions to get started on a hello-world level. The samples on the d3.js site are bit too complex for a noob. But browsing through the example folder of the d3.js download helps, and usually you learn most dissecting by re-assembling sample code from other people. Another great source is gist.github.com, a code snippet repository. Look for d3.js ! With bl.ocks.org you can even “run” the snippets.

The treeview is a classic visualization but one of my favorites, specifically if you spice it up with interaction and allow the user to dive into a subtree of his choice. But what is the most simple tree layout ? I want to understand the physics behind it. So let me share my compiled (of different samples) most simple version without any fancy features or interaction.

Simlpe Tree Layout

Here my bl.ocks.org version with code or here to copy and paste:

Continue reading

ZK and d3.js

One of the important questions to me: Can I embed d3.js in my ZK zul pages and talk to the visualization ? Embedding is fairly simple, using the html tag you can embed any native html content and scripts. There is certainly a limitation to scripts, as the final rendered html page will contain both the zk javascript and our script, hoping there is no interference. As sample it is not possible to mix ZK with ExtJS, but JQuery is not a problem.

Task 1: Most simple zk application (Draw circle)

d3.js getting started

I love visualization of data. It is fantastic what and how you can visualize data and make it accessible and understandable. Specifically I like tree, radial trees and graphs . While the tools some years back were rather restricted to thick clients and Flash applications, we can transport great visualizations with the means of a simple (recent) browser.I recommend this book ‘Beautiful Visualization’ by Julie Steele, Noah Iliinsky (link)

For a while I worked wth prefuse and flare (2 nice but more or less defunc projects), now I start to implement some real life applications with d3.js (link). The features are awesome but the documentation is still rather short, the API doc is complete, but not much hello world stuff to get started with, other than dissecting some of the sample in the download.

What do we need to get started ?

  • A browser and a web server (for Linux users: there is one build in your machine, just start python -m SimpleHTTPServer 8888 and the current path becomes ‘server’)
  • Download d3.js (comes with plenty of samples, some of them will NOT run when you open the html files as file, use the webserver instead!)
  • Text editor (Kate, vi,..)

What is the most simple visualization sourcecode ?

  • Create a html file and place the d3.js in the same or lib folder.
  • Lets draw a circle (I took this from one of the get-started blogs by Christophe Viau, link)
    <!DOCTYPE html>
    <html>
      <head>
        <title>Hello, data!</title>
        <script type="text/javascript" src="lib/d3.js"></script>
      </head>
      <body>
    
        <div id="viz"></div>
    
        <script type="text/javascript">
    
        var sampleSVG = d3.select("#viz")
            .append("svg:svg")
            .attr("width", 100)
            .attr("height", 100);
    
        sampleSVG.append("svg:circle")
            .style("stroke", "black")
            .style("fill", "white")
            .attr("r", 40)
            .attr("cx", 50)
            .attr("cy", 50)
    
        </script>
    
      </body>
    </html>
    
  • Open the browser

    Most simple d3.js sample

I hope I find the time to share more with you once I get the grip on this tool.

ZK ‘Client-Server’ Communication Sample Part 2

In the first part (link) we made a javascript embedded into our zul page send data to the controller with the magic zau.send() function. The reverse can be done too, call a javascript on the zul page from the controller.

Lets continue with the sample from part 1: