D3.js : SELECTION

I am totally newbie in D3, so don’t expect me to share an advance tutorial for D3 XD I am still learning and this post would just be my another self-notes, wherever or whenever i need it :’)

This would be my first post about D3, and i just wanna share about what i think it’s important if you wanna start learning D3. Well, actually when i first try it, just look at the library, check the examples, download the code and try to run it inside my project. And it works fine. But, when i wanna go deeper about D3, like, you know, start to customize the view, i need to learn more about it and what i got first, i think about it’s Selection; I think it’s an important thing since to modify element, syling or adding event/action, i need to learn how i make selection to the element i want first.

Well, i’m not start by ‘how to make the chart/element’ bcz, as you know, i just download some chart already on github or bl.ocks.org/d3indepth XD sorry. But if you interested, you can visit this helpfull article right here : https://www.dashingd3js.com/

Okay, so we’ll start. I am already make the graph, like forced-directed graph, consist of nodes and links (the line to connect the nodes). And, i start to customize it. D3 selections allow DOM elements to be selected in order to do something with them, be it changing style, modifying their attributes, performing data-joins or inserting/removing elements. (http://d3indepth.com/selections/) – btw you should visit the site, it really helpful. In D3 we use SVG element.

Scalable Vector Graphics (SVG)

Scalable Vector Graphics (SVG) is a family of specifications for creating two-dimensional vector graphics. Vector graphics are not created out of pixels. Vector graphics are created with paths having a start and end point, as well as points, curves and angles in between. Since Vector Graphics are not created out of pixels, they can be scaled up to larger or smaller sizes without losing image quality.

SVG images and their behaviors are defined in XML text files. The XML text can be included in an HTML document. This text means that images can be created and edited in a text editor. Also, since the DOM includes XML as part of the DOM specification, we can use the DOM Tree to access and update the structure, content and style of SVG Images.

SVG comes with a basic set of shape elements:

  • Rectangle
  • Circle
  • Ellipse
  • Straight Line
  • Polyline
  • Polygon

Okay, i already make a force-directed-graph that looks like this :

D3 – forced network

Okay, it’s only circles (nodes) and links btw. But if you learn D3, you will need to check the element inspector ( i prefer use chrome). Why? Because it will help us to make selection. As you see on D3, we just write code like this :

var svg = d3.select("svg"),
width = +svg.attr("width"), height = +svg.attr("height");  

var node = g.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes_data)
.enter()
.append("circle")
.attr("r", radius)
.attr("fill", circleColour);

and the result is as you can see above ( on the picture), but then we check inspector, and we got like this :

circle d3

Elements

You can see the <g> tag , it is the SVG Group Element is a container that contains all child SVG elements defined inside of it and that share the same attribute. In the example, it have 2 groups. One contains lines and the others contain circles. And there’s many circle elements that created with D3, we use .append("circle")and its populate the element as we can see in the element inspector.

D3 has two functions to make selections d3.select and d3.selectAll.

d3.select selects the first matching element whilst d3.selectAll selects all matching elements. Each function takes a single argument which specifies the selector string. Examples, we want to select all the circles, we can use d3.selectAll(“circle”); And when we use d3.select(“circle”); it will select the first matching element, only one, the first one. In my example, it is the line that i blocked. We can also select item by it class like d3.selectAll(“.classname”);

We can also updating the elements with functions, like this :

d3.selectAll('circle')
  .attr('cx', function(d, i) {
    return i * 100;
  });

The function typically accepts two arguments d and i. The first argument d is the joined data and i is the index of the element within the selection. If we want to update elements in a selection according to their position within the selection, we can use the iargument. For example to position some rect elements horizontally we can use: (http://d3indepth.com/selections/)

When i added events,  i add a function and i want to change radius of the element i clicked (for example) i can use “this“, so it will look like :

d3.select(this); and i can also modify element, like d3.select(this).attr('radius', 10);

d3 styling change radius

d3 styling change radius

We can also make selection like this:

// Add .selected class to 3rd circle
d3.select('circle:nth-child(3)')
	.classed('selected', true);

// Set checked property of checkbox
d3.select('input.robot-checkbox')
	.property('checked', true);

So it will just modify the element clicked, and change radius to 10.  You can also adding text, title, or changing the color, add borders etc, but i will write more about modifying element and styling on my next post ! See youu very sooon 🙂

Advertisements

D3.js : Handling Event (Click, MouseOver and MouseOut)

Okay, after my previous post about D3 selection and modifying elements.. (sorry if its not well arranged), now i want to share about how to add event in D3.js. Some events ,  like, on-click event, on-mouseover, mouseout, etc.

I have a circle :

var circleAttrs = {
          cx: function(d) { return xScale(d.x); },
          cy: function(d) { return yScale(d.y); },
          r: radius
      };

Click Event

svg.on("click", function() {
          var coords = d3.mouse(this);
          svg.selectAll("circle")  // For new circle, go through the update process
            .data(dataset)
            .enter()
            .append("circle")
            .attr(circleAttrs)  // Get attributes from circleAttrs var
            .on("mouseover", handleMouseOver)
            .on("mouseout", handleMouseOut);
        });

Mouseover and MouseOut

// Create Event Handlers for mouse
      function handleMouseOver(d, i) {  // Add interactivity

            // Use D3 to select element, change color and size
            d3.select(this).attr({
              fill: "orange",
              r: radius * 2
            });

            // Specify where to put label of text
            svg.append("text").attr({
               id: "t" + d.x + "-" + d.y + "-" + i,  // Create an id for text so we can select it later for removing on mouseout
                x: function() { return xScale(d.x) - 30; },
                y: function() { return yScale(d.y) - 15; }
            })
            .text(function() {
              return [d.x, d.y];  // Value of the text
            });
          }

      function handleMouseOut(d, i) {
            // Use D3 to select element, change color back to normal
            d3.select(this).attr({
              fill: "black",
              r: radius
            });

            // Select text by id and then remove
            d3.select("#t" + d.x + "-" + d.y + "-" + i).remove();  // Remove text location
          }

handleMouseOver is function to handle mouseover event, occurs when the mouse pointer is over the selected element. The mouse over only triggered when the mouse enter the selected elements. On the code above, will make the selected element fill color is orange and the radius 2x the existing radius. then append text to selected elements, valued it’s position (dx and dy)

handleMouseOut The mouseout event occurs when the mouse pointer leaves the selected element. The mouseout() method triggers the mouseout event, or attaches a function to run when a mouseout event occurs. The mouseleave event only triggers when the mouse pointer leaves the selected element. On the example, mouseout function will make the element fill color into black, and set the radius; then also remove the elements with id #t.

D3.js : Modifying Elements

After selecetion, i would like to share about styling in D3.js. Modifying element atribut like change the circle radius, color, width, stroke, fill color etc, it means we change the style, so i called it styling.

I will make it so simple, so i have a circle like this :

var svg = d3.select(“svg”),
width = +svg.attr(“width”),
height = +svg.attr(“height”);

svg.append(“circle”) // attach a circle
.attr(“cx”, 200) // position the x
.attr(“cy”, 100) // position the y
.attr(“r”, 50) // set the radius
.style(“fill”, “red”); // set the fill

 

There’s some atribut  like x and y position, the radius and fill color. If we want no color just add .style(“fill”, “none”). And we can also add color like  (.style("fill", "rgb(255,0,0)");) or in hexadecimal (.style("fill", "#f00");)

Styles in D3:

  • fill
  • stroke
  • opacity
  • fill-opacity
  • stroke-opacity
  • stroke-width
  • stroke-dassharay
  • stroke-linecap
  • stroke-linejoin
  • writing-mode
  • glyph-orientation-vertical

I added some styles to the circle, and then it look like this :

 

d3.select(“circle”) // select a circle
.attr(“cx”, 200) // position the x
.attr(“cy”, 100) // position the y
.attr(“r”, 50) // set the radius
.style(“fill”, “red”) // set the fill colour
.style(“fill-opacity”, 0.4) // set fill opacity
.style(“stroke”, “blue”) // set the line color
.style(“stroke-width”, 3 ) // set the line width
.style(“stroke-dasharray”, (“10,3”)) // make the stroke dashed

Then, i tried to make lines and add some styles, looks like this:

svg.append(“line”) // attach a line
.style(“stroke”, “blue”) // colour the line
.style(“stroke-width”, 20) // adjust line width
.style(“stroke-linecap”, “butt”) // stroke-linecap type
.attr(“x1”, 100) // x position of the first end of the line
.attr(“y1”, 50) // y position of the first end of the line
.attr(“x2”, 300) // x position of the second end of the line
.attr(“y2”, 50); // y position of the second end of the line

svg.append(“line”) // attach a line
.style(“stroke”, “blue”) // colour the line
.style(“stroke-width”, 20) // adjust line width
.style(“stroke-linecap”, “round”) // stroke-linecap type
.attr(“x1”, 100) // x position of the first end of the line
.attr(“y1”, 100) // y position of the first end of the line
.attr(“x2”, 300) // x position of the second end of the line
.attr(“y2”, 100); // y position of the second end of the line

svg.append(“line”) // attach a line
.style(“stroke”, “blue”) // colour the line
.style(“stroke-width”, 20) // adjust line width
.style(“stroke-linecap”, “square”) // stroke-linecap type
.attr(“x1”, 100) // x position of the first end of the line
.attr(“y1”, 150) // y position of the first end of the line
.attr(“x2”, 300) // x position of the second end of the line
.attr(“y2”, 150); // y position of the second end of the line

Attrributes in D3:

      • xy ;
        Using the x and y attributes places the anchor points for these elements at a specified location. Of the elements that we have examined thus far, the rectangle element and the text element have anchor points to allow them to be positioned
      • x1x2y1y2

        • x1: The x position of the first end of the line as measured from the left of the screen.
        • y1: The y position of the first end of the line as measured from the top of the screen.
        • x2: The x position of the second end of the line as measured from the left of the screen.
        • y2: The y position of the second end of the line as measured from the top of the screen.
      • points
        The points attribute is used to set a series of points which are subsequently connected with a line and / or which may form the bounds of a shape. These are specifically associated with the polyline and polygonelements. Like the xy and x1x2y1y2 attributes, the coordinates are set from the top, left hand corner of the web page.
        The data for the points is entered as a sequence of x,y points in the following format;
        .attr("points", "100,50, 200,150, 300,50");
      • cxcy

        The cxcy attributes are associated with the circle and ellipse elements and designate the centre of each shape. The coordinates are set from the top, left hand corner of the web page.
        • cx: The position of the centre of the element in the x axis measured from the left side of the screen.
        • cy: The position of the centre of the element in the y axis measured from the top of the screen.
      • r, to set radius of the element
        .attr("5", "50");
      • rx, ry
        The rxry attributes are associated with the ellipse element and designates the radius in the x direction (rx) and the radius in the y direction (ry).
        • rx: The radius of the ellipse in the x dimension from the cxcy position to the perimeter of the ellipse.
        • ry: The radius of the ellipse in the y dimension from the cxcy position to the perimeter of the ellipse.
        • translate: Where the element is moved by a relative value in the x,y direction.
        • scale: Where the element’s attributes are increased or reduced by a specified factor.
        • rotate: Where the element is rotated about its reference point by an angular value.transform (translate(x,y), scale(k), rotate(a)) 
          The transform attribute is a powerful one which allows us to change the properties of an element in several different ways.
          .attr("transform", "translate(50,50)") // translate the circle
          .attr("transform", "scale(2)"); // scale the circle attributes

          The translate-rotate attribute will rotate an element and its attributes by a declared angle in degrees.

          svg.append("text") // append text
          .style("fill", "black") // fill the text with the colour black .attr("x", 200) // set x position of left side of text
          .attr("y", 100) // set y position of bottom of text
          .attr("dy", ".35em") // set offset y position .attr("text-anchor", "middle") // set anchor y justification .attr("transform", "rotate(10)") .text("Hello World"); // define the text to display
      • widthheight 

        width and height are required attributes of the rectangle element. width designates the width of the rectangle and height designates the height (If you’re wondering, I often struggle defining the obvious).

      • text-anchor

        The text-anchor attribute determines the justification of a text element
        Text can have one of three text-anchor types;
        • start where the text is left justified.
        • middle where the text is centre justified.
        • end where the text is right justified
      • dxdy
        dx and dy are optional attributes that designate an offset of text elements from the anchor point in the x and y dimension . There are several different sets of units that can be used to designate the offset of the text from an anchor point. These include em which is a scalable unit, px (pixels), pt (points (kind of like pixels)) and %(percent (scalable and kind of like em))
      • lenghtAdjust

        The lengthAdjust attribute allows the textLength attribute to have the spacing of a text element controlled to be either spacing or spacingAndGlyphs;
        • spacing: In this option the letters remain the same size, but the spacing between the letters and words are adjusted.
        • spacingAndGlyphs: In this option the text is stretched or squeezed to fit
      • textLength
        The textLength attribute adjusts the length of the text to fit a specified value.

And also i have summaries :

Source :

http://www.d3noob.org/2014/02/styles-in-d3js.html

http://www.d3noob.org/2014/02/attributes-in-d3js.html

http://www.tutorialsteacher.com/d3js

It’s a very useful site btw, i highly recommend you to visit the site if you wanna learn about D3 (as beginner). But so sad that the last post on that site in 2016. There’s some version D3, try the latest (V4)

Shiny from R Studio

Shiny is an R package that makes it easy to build interactive web apps straight from R. You can host standalone apps on a webpage or embed them in R Markdown documents or build dashboards. You can also extend your Shiny apps with CSS themes, htmlwidgets, and JavaScript actions. (http://shiny.rstudio.com/)

At least, that’s the sentences i read when i start to googling about Shiny. And, R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment which was developed at Bell Laboratories (formerly AT&T, now Lucent Technologies) by John Chambers and colleagues. R can be considered as a different implementation of S. There are some important differences, but much code written for S runs unaltered under R. (https://www.r-project.org/about.html)

Shiny Features :

  • Build useful web applications with only a few lines of code—no JavaScript required.
  • Shiny applications are automatically “live” in the same way that spreadsheets are live. Outputs change instantly as users modify inputs, without requiring a reload of the browser.
  • Shiny user interfaces can be built entirely using R, or can be written directly in HTML, CSS, and JavaScript for more flexibility.
  • Works in any R environment (Console R, Rgui for Windows or Mac, ESS, StatET, RStudio, etc.)
  • Attractive default UI theme based on Twitter Bootstrap.
  • A highly customizable slider widget with built-in support for animation.
  • Pre-built output widgets for displaying plots, tables, and printed output of R objects.
  • Fast bidirectional communication between the web browser and R using the websockets package.
  • Uses a reactive programming model that eliminates messy event handling code, so you can focus on the code that really matters.
  • Develop and redistribute your own Shiny widgets that other developers can easily drop into their own applications (coming soon!).
    (http://rstudio.github.io/shiny/tutorial/)

Well, as i am currently learning about data visualization, so i hv to learn about some tools to create graph for visualisizing the data. There are some tools i can use, but i still learn of it. So many things i should learn, and i think i can start it. But, may be i just need time to understand it all. Well, and this is would be my first post about R and it’s Shiny project. I’ll write some post later and give you some sample code, cheers!

How to make Bar Chart in YII Framework (using ext yii.Highcharts)

Hello again everyone, this last few weeks, i’ve been dealing with Graph in Java Web, espescially using D3.js but i’ll share about D3 in my next post may be.

Last time i posted about Yii Framework and now i will add one more post about it. Now, i want to share just a simple post (again) about how to make charts in Yii Framework. Well, may be you notice that i really like to use yii framework to my side-projects (outside of my works in the office building). Yes, i really like it. One of my reason is i can do the things in yii easily and more efficient code. Like one in THIS POST.

Well, back to Highcharts~ On my last projects, turns out that i need to make some graph on it, then, ok i will try some of it. One of the way to make it is using yii extension, and one of the famous one is Yii Highcharts. Well, now i will share about how to using it in my yii projects.

First, we need to download and extract yii.highchart extenstion inside protected/extensions folder. Do not forget to remove the version number in the folder name. Just like this :

Now, we need to modify config/main.php to add yii.highchart extension, on this line :

// autoloading model and component classes
‘import’=>array(
‘application.models.*’,
‘application.components.*’,
‘ext.yii-highcharts.*’,
‘ext.print.*’,
),

then we can use highchart extension like this -> “ext.yii-highcharts.highcharts.HighchartsWidget”

And we’re ready to use our highchart ext.

// BEGIN BAR CHART
$this->widget(‘ext.yii-highcharts.highcharts.HighchartsWidget’, array(
‘options’=>array(
‘chart’=> array(‘defaultSeriesType’=>’column’,),
‘title’ => array(‘text’ => ‘Fruits’),
‘legend’=>array(‘enabled’=>false),
‘xAxis’=>array(‘categories’=>array(‘Apples’, ‘Mangos’, ‘Strawberries’, ‘Grapes’, ‘Oranges’),),
‘yAxis’=> array(
‘min’=> 0,
‘title’=> array(
‘text’=>’Total’
),
),
‘series’ => array(
array(‘data’ => array(10,9,13,15,20))
),
‘tooltip’ => array(‘formatter’ => ‘js:function() {return “<b>”+ this.x +”</b><br/>”+”Fruits : “+ this.y; }’),
‘plotOptions’=>array(‘pie’=>(array(
‘allowPointSelect’=>true,
‘showInLegend’=>true,
‘cursor’=>’pointer’,
)
)
),
‘credits’=>array(‘enabled’=>false),
)
));

And the chart will looks like this :

Also, we can configure more about the chart widgets where you can read more here -> http://www.yiiframework.com/extension/highcharts/

Okay , that’s all. A very very simple post this morning. Btw, i”ve used plugin for syntax highlighter years ago, but looks like it doesn’t appear anymore. T.T

How to Generate Signed APK – Android Studio

This is another note for me, hehe. This is step from make new key and make signed apk.

  1. In the menu bar, Click Build > Generate Signed APK
  2. Click Create New

    • Key store path: Select the location where your keystore should be created.
    • Password: Create and confirm a secure password for your keystore. On the new keystore, we must fill the form.
    • Alias: Enter an identifying name for your key.
    • Password: Create and confirm a secure password for your key. This should be different from the password you chose for your keystore
    • Validity (years): Set the length of time in years that your key will be valid. Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
    • Certificate: Enter some information about yourself for your certificate. This information is not displayed in your app, but is included in your certificate as part of the APK.
  3. Select apk destination folder, build type : release. Choose signature version and then click Finish!
  4. Open in File explorer, and there is your signed APK : yourprojectname/app/build/outputs/apk /app-release.apk
  5. Done!

It’s a very short post but thank you for visit.

Generate CRUD in Yii Project using Gii

This time, i will share about how to Generate code with Gii – in Yii Framework.

Last time, i got some projects, web based and i decided to use Yii to saved time. Bcz its easier, and provides Crud Generator , so it will make it faster in this short-time project. And, i use yii bcz it’s more familiar for me. And this is just a note for my self so dont hv to browse again.

  1. Make sure you already have database, and make your table. Ex: User
  2. Open URL : http://localhost/[YOUR_PROJECT_NAME]/gii/default/login
    use your login password, that you can find on config folder/ main.php, on this line :
    uncomment this line and just change your password:
    ‘gii’=>array(
    ‘class’=>’system.gii.GiiModule’,
    ‘password’=>’YOURPASSWORD HERE’,
    // If removed, Gii defaults to localhost only. Edit carefully to taste.
    ‘ipFilters’=>array(‘127.0.0.1′,’::1′),
    ),
  3. Click Generate Model -> Fill the texfield with your table name , ex “user” -> Click Preview -> Generate
  4. Click Generate Crud -> Type your model class name -> ex: “User” -> Click Preview -> Generate. When you’re on this step, its done.
  5. Test with access URL : http://localthost/user
    Ups, never let your password shown like that!
  6. Finish! Thanks!