Nat  Grady

Nat Grady

1660074360

ScatterD3: R Scatter Plot Htmlwidget Based on D3.js

ScatterD3 

scatterD3 is an HTML R widget for interactive scatter plots visualization. It is based on the htmlwidgets R package and on the d3.js javascript library.

Features

Here is a small preview of what you will get :

example

  • The visual guide gives a list of features and examples.
  • The sample shiny app allows to live test the package features and its shiny integration.

Installation

Install from CRAN :

install.packages("scatterD3")

Or from Github for the latest development version :

remotes::install_github("juba/scatterD3")

Usage

Quick example of the scatterD3 function based on the mtcars dataset :

mtcars$names <- rownames(mtcars)
scatterD3(data = mtcars, x = wt, y = mpg, lab = names,
          col_var = cyl, symbol_var = am,
          xlab = "Weight", ylab = "Mpg", col_lab = "Cylinders",
          symbol_lab = "Manual transmission")

See the visual guide for a step-by-step guide and details about the different function arguments.

scatterD3 provides a built-in SVG export of the current widget view. As an HTML widget, you can also include it in an Rmarkdown HTML document while keeping its interactive features.

Shiny integration

Like every R HTML widget, shiny integration is straightforward. But as a D3 widget, scatterD3 is updatable : changes in settings or data can be displayed via smooth transitions instead of a complete chart redraw, which can provide interesting visual clues.

Furthermore, scatterD3 provides some additional handlers and callback hooks for a more complete JavaScript interactivity and integration.

The sample scatterD3 shiny app allows you to see the different features described here. You can check its source code on GitHub and the visual guide for a better understanding of the different arguments.

Development notes

This package uses packer to manage JavaScript source code and dependencies. If you want to modify it, you'll need a working installation of Node.js.

After cloning this repository, run the following in a terminal at the project root :

npm install --production=false

Then, if you modify the JavaScript code in srcjs, you'll have to run the following command to bundle and update the widget JavaScript code :

packer::bundle_dev()

If you want to ship a minimized production version, use :

packer::bundle_prod()

Credits

This package has been made possible by :

Download Details:

Author: juba
Source Code: https://github.com/juba/scatterD3 

#r #d3 #html #widgets 

ScatterD3: R Scatter Plot Htmlwidget Based on D3.js
Nat  Grady

Nat Grady

1660002900

D3heatmap: A D3.js-based Heatmap Htmlwidget for R

D3 Heatmap for R

This is an R package that implements a heatmap htmlwidget. It has the following features:

  • Highlight rows/columns by clicking axis labels
  • Click and drag over colormap to zoom in (click on colormap to zoom out)
  • Optional clustering and dendrograms, courtesy of base::heatmap

Example

Installation

To install:

if (!require("devtools")) install.packages("devtools")
devtools::install_github("talgalili/d3heatmap")

Usage

Like any htmlwidget, you can visualize a d3 heatmap directly from the R console:

library(d3heatmap)
d3heatmap(mtcars, scale = "column", colors = "Spectral")

You can also include them in R Markdown chunks, or use them in Shiny applications with the d3heatmapOutput and renderD3heatmap functions.

See ?d3heatmap for options.

Modern API

Inspired by dygraphs and able to leverage magrittr, the new API provides a second method for invoking d3heatmap and integrating with Shiny apps, modules, and gadgets! Examples:

library(d3heatmap)
library(magrittr)

d3heatmap(mtcars, dendrogram = 'none', key = TRUE, col = 'RdYlGn',
          scale = 'column', key.title = "Legend", print.values = T,
          notecol = 'white') %>% 
  hmAxis("x", title = "test", location = 'bottom') %>% 
  hmAxis("y", title = "test", location = 'left') %>% 
  hmCells(font.size = 8, color = 'blue') %>% 
  hmLegend(show = T, title = "Title", location = "tl")
  

Side colors

library(d3heatmap)
library(magrittr)

rsc<-matrix(rep_len(c('good', 'bad', 'ugly'), length.out = 64), ncol = 2)
rsccols<-c('red', 'white', 'blue')
rscnames <- c('Row 1', 'Row 2')

csc<-matrix(rep_len(c('first', 'second', 'third', 'fourth', 'fifth'), length.out = 33), nrow = 3)
csccols<-c('orange', 'blue', 'grey', 'green', 'red')
cscnames <- c('Column 1', 'Column 2', 'Column 3')

library(d3heatmap)
d3heatmap(mtcars,
          key = TRUE, scale = 'column', 
          key.title = "Legend", 
          col = 'RdYlGn',
          srtCol = 30, 
          breaks = 8,
          xlab = 'test',
          ylab = 'TEST',
          print.values = T,
          density.info = 'histogram',
          denscol = 'grey',
          sideCol = 3,
          sideRow = 4,
          RowSideColors = rsc,
          ColSideColors = csc,
          RowColorsPalette = rsccols,
          ColColorsPalette = csccols,
          RowColorsNames = rscnames,
          ColColorsNames = cscnames)

## using the modern API:

d3heatmap(mtcars, key = TRUE, scale = 'none') %>% 
  hmSideColors(axis = 'column', side.colors = csc,
    palette = csccols, names = cscnames) %>% 
  hmSideColors(axis = 'y', side.colors = rsc,
    palette = rsccols, names = rscnames)
    

NEWS from recent PR

__2018-02-24 Gadget

An shiny gadget coupled with an S4 class that provides print() and save() methods. Gadget takes normal d3heatmap inputs and allows for interactive adjustment of the heatmap. Gadget allows for filtering rows and columns, and also a dynamic filter to interatively subset the entire underlying data set. Saving the gadget to an object generates the S4 class that contains the heatmap, data, filter, and settings. Passing the gadget back into the function d3heatmapGadget(gadget) starts the user at the last state of the gadget.

gadget <- d3heatmapGadget(mtcars, col = 'blues')
print(gadget)
save(gadget, file = "heatmap.html")
gadget <- d3heatmapGadget(gadget)
    

2018-01-13 Side colors

Based on example contributions and forks from several people, the side colors components of heatmap.2 and heatmap.3 have been added! Functionality includes color labels, axis labels for the color sections, and hover info. Further alignment of the old API parameters to heatmap.2 and heatmap.3, plus heatmap.2/3 and the modern API were implemented for side colors. the Readme, package news and examples were also updated.

2017-12-17 New API!!

The master branch now includes a newer, modern API, motivated by the main d3heatmap fork's desire for a new API and inspired by the API of the dygraphs package produced by RStudio. The new API takes advantage of magrittr piping and offers smaller functions to modify selected portions of the heatmap. I have conducted good, but by no means exhaustive, testing... so feel free to poke around, find bugs, and open up issues or PRs for them.

d3heatmap is not actively developed, but I will accept PR. You might consider using heatmaply, which is based on plotly (it comes with more features, but is not based on d3)

Download Details:

Author: Talgalili
Source Code: https://github.com/talgalili/d3heatmap 
License: View license

#r #d3 #map 

D3heatmap: A D3.js-based Heatmap Htmlwidget for R
Monty  Boehm

Monty Boehm

1659671880

A Step By Step Guide to D3.js Chart Usage in Ijulia Notebooks

Workflow:

  • create dummy data to experiment with chart
  • write d3 chart as script that is loaded in index.html file
  • transform Javascript script to function:
    • in index.html file:
      • select canvas
      • set customized parameters
      • load data
    • in function:
      • set default parameters, create access functions
      • remove data loading
      • create inner function: based on selection and data
  • create Julia API:
    • save data to disk
    • alternatively: directly write data to Javascript code
    • TODO: print warning that data is written to disk
    • load data in Javascript
    • forward chart options to Javascript
    • call chart
    • return full Javascript code
    • TODO: include CSS somehow

Original article source at: https://github.com/cgroll/ijulia_d3_tutorial 

#julia #d3 

A Step By Step Guide to D3.js Chart Usage in Ijulia Notebooks
Monty  Boehm

Monty Boehm

1659656880

DThree.jl: Simple interface to D3.js From Julia

Simple interface to d3 (http://d3js.org) and other JavaScript libraries for chart making.

This package for Julia provides a simple interface for using d3 syntax within julia.

It isn't very clever, basically it takes a d3 command like:

d3.selectAll("p").style("color", "white")

And turns it into a julia call like:

d3.selectAll("p").style("color", "white")

(Only after)

using DThree
d3 = D3()

Okay, you might guess the style. This just pieces together a string of JavaScript that will get inserted into a web page.

The implementation is pretty stupid, it just makes fields named after the main methods and creates a function when the object is instantiated. The functions return a D3 instance so they can be chained, as above.

If the field isn't present, then the interface can look one of two ways:

d3[:selectAll]("p")._("color", "white") ## two ways [:symbol](args...) or _("meth", args...)

By default, strings are quoted. To stop that, wrap the string in asis (like R's I operator). This is necessary when the argument refers to a JavaScript object.

using DThree
style = """
.chart div {
  font: 10px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
  }
"""
  
w = figure()
DThree.empty_page(w, style=style) # loads D3 libraries

d3 = D3()
d3.select("body").append("div").attr("class", "chart") |> js

data = [4,8,16,23,42]

d3.select(".chart").selectAll("div").
    data(data).
      enter().append("div").
       style("width", asis"""function(d) { return d * 10 + "px"; }""").
         text(asis"""function(d) { return d; }""")  |> js
    

The js call comes from Blink, as does the figure object.

Blink

This package also borrows the figure manipulation tools of Immerse and the HTML windows of Blink to create canvases to manipulate. The basic idea would follow from this example

using DThree, Plots; plotly()
w = figure()
Blink.title(w, "title")
plot(sin, 0, 2pi)
plot!(cos)

Author: jverzani
Source Code: https://github.com/jverzani/DThree.jl 
License: MIT license

#julia #d3 

DThree.jl: Simple interface to D3.js From Julia
Reid  Rohan

Reid Rohan

1658329080

Plottable: A Library Of Modular Chart Components Built on D3

Plottable.js 

Overview

Plottable.js is a library of chart components for creating flexible, custom charts for websites. It is built on top of D3.js and provides higher-level pieces, like plots, gridlines, and axes. As such, it's easier to quickly build charts than with D3, and the charts are much more flexible than standard-template charts provided by charting libraries. You can think of Plottable as a "D3 for Charts" — it is not a charting library but rather a library of chart components. Check out examples of Plottable on our website's examples page.

Philosophy

Plottable's core philosophy is "Composition over Configuration", so a lot of the API flexibility is in choosing which Components to use, and how to arrange them in Tables, rather than setting high-level properties on the charts. If you find you need a feature that doesn't exist, consider writing a new Component that implements the functionality. This way, you can get your custom functionality and still benefit from the rest of the library.

Plottable.js is being developed by Palantir Technologies. It's developed in TypeScript and distributed in ES5 JavaScript.

Quick Start

Upgrading to v1.0.0

If you are upgrading from a pre-v1.0.0 version of Plottable to v1.0.0 or later, please use the Upgrade Guide on the wiki.

We Want To Help!

If you run into any problems using Plottable, please let us know. We want Plottable to be easy-to-use, so if you are getting confused, it is our fault, not yours. Create an issue and we'll be happy to help you out, or drop by our Gitter room.

Development

  • Clone the repo
  • Install global dependencies sudo npm install grunt grunt-cli typescript -g
  • Install local dependencies npm install
  • Run grunt and it will spin up a server (pointed at localhost:9999) and begin compiling the typescript code

Contributing

  • Write your code
  • Add tests for new functionality, and please add some quicktests too
  • Run grunt test and verify it completes with no warnings or failures
  • Commit new files, including the updated built files like plottable.js and plottable.d.ts
  • Fill out the Personal or Corporate Contributor License Agreement and send it to opensource@palantir.com
    • You can do this easily on a Mac by using the Tools - Annotate - Signature feature in Preview.
  • Submit a pull request

Author: Palantir
Source Code: https://github.com/palantir/plottable 
License: MIT license

#javascript #d3 #chart #typescript 

Plottable: A Library Of Modular Chart Components Built on D3
Reid  Rohan

Reid Rohan

1658321700

Plotly.js: Open-source JavaScript Charting Library Behind Plotly, Dash

Plotly.js is a standalone Javascript data visualization library, and it also powers the Python and R modules named plotly in those respective ecosystems (referred to as Plotly.py and Plotly.R).

Plotly.js can be used to produce dozens of chart types and visualizations, including statistical charts, 3D graphs, scientific charts, SVG and tile maps, financial charts and more.

 

Contact us for Plotly.js consulting, dashboard development, application integration, and feature additions.


Load as a node module

Install a ready-to-use distributed bundle

npm i --save plotly.js-dist-min

and use import or require in node.js

// ES6 module
import Plotly from 'plotly.js-dist-min'

// CommonJS
var Plotly = require('plotly.js-dist-min')

You may also consider using plotly.js-dist if you prefer using an unminified package.


Load via script tag

The script HTML element

In the examples below Plotly object is added to the window scope by script. The newPlot method is then used to draw an interactive figure as described by data and layout into the desired div here named gd. As demonstrated in the example above basic knowledge of html and JSON syntax is enough to get started i.e. with/without JavaScript! To learn and build more with plotly.js please visit plotly.js documentation.

<head>
    <script src="https://cdn.plot.ly/plotly-2.13.1.min.js"></script>
</head>
<body>
    <div id="gd"></div>

    <script>
        Plotly.newPlot("gd", /* JSON object */ {
            "data": [{ "y": [1, 2, 3] }],
            "layout": { "width": 600, "height": 400}
        })
    </script>
</body>

Alternatively you may consider using native ES6 import in the script tag.

<script type="module">
    import "https://cdn.plot.ly/plotly-2.13.1.min.js"
    Plotly.newPlot("gd", [{ y: [1, 2, 3] }])
</script>

Fastly supports Plotly.js with free CDN service. Read more at https://www.fastly.com/open-source.

Un-minified versions are also available on CDN

While non-minified source files may contain characters outside UTF-8, it is recommended that you specify the charset when loading those bundles.

<script src="https://cdn.plot.ly/plotly-2.13.1.js" charset="utf-8"></script>

Please note that as of v2 the "plotly-latest" outputs (e.g. https://cdn.plot.ly/plotly-latest.min.js) will no longer be updated on the CDN, and will stay at the last v1 patch v1.58.5. Therefore, to use the CDN with plotly.js v2 and higher, you must specify an exact plotly.js version.

MathJax

You could load either version two or version three of MathJax files, for example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_SVG.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.js"></script>

When using MathJax version 3, it is also possible to use chtml output on the other parts of the page in addition to svg output for the plotly graph. Please refer to devtools/test_dashboard/index-mathjax3chtml.html to see an example.

Bundles

There are two kinds of plotly.js bundles:

  1. Complete and partial official bundles that are distributed to npm and the CDN, described in the dist README.
  2. Custom bundles you can create yourself to optimize the size of bundle depending on your needs. Please visit CUSTOM_BUNDLE for more information.

Alternative ways to load and build plotly.js

If your library needs to bundle or directly load plotly.js/lib/index.js or parts of its modules similar to index-basic in some other way than via an official or a custom bundle, or in case you want to tweak the default build configurations of browserify or webpack, etc. then please visit BUILDING.md.


Documentation

Official plotly.js documentation is hosted at https://plotly.com/javascript.

These pages are generated by the Plotly graphing-library-docs repo built with Jekyll and publicly hosted on GitHub Pages. For more info about contributing to Plotly documentation, please read through contributing guidelines.


Bugs and feature requests

Have a bug or a feature request? Please open a Github issue keeping in mind the issue guidelines. You may also want to read about how changes get made to Plotly.js


Contributing

Please read through our contributing guidelines. Included are directions for opening issues, using plotly.js in your project and notes on development.


Notable contributors

Plotly.js is at the core of a large and dynamic ecosystem with many contributors who file issues, reproduce bugs, suggest improvements, write code in this repo (and other upstream or downstream ones) and help users in the Plotly community forum. The following people deserve special recognition for their outsized contributions to this ecosystem:

 GitHubTwitterStatus
Alex C. Johnson@alexcjohnson Active, Maintainer
Mojtaba Samimi@archmoj@solarchvisionActive, Maintainer
Antoine Roy-Gobeil@antoinerg Active, Maintainer
Nicolas Kruchten@nicolaskruchten@nicolaskruchtenActive, Maintainer
Jon Mease@jonmmease@jonmmeaseActive
Étienne Tétreault-Pinard@etpinard@etpinardHall of Fame
Mikola Lysenko@mikolalysenko@MikolaLysenkoHall of Fame
Ricky Reusser@rreusser@rickyreusserHall of Fame
Dmitry Yv.@dy@DimaYvHall of Fame
Robert Monfera@monfera@monferaHall of Fame
Robert Möstl@rmoestl@rmoestlHall of Fame
Nicolas Riesco@n-riesco Hall of Fame
Miklós Tusz@mdtusz@mdtuszHall of Fame
Chelsea Douglas@cldougl Hall of Fame
Ben Postlethwaite@bpostlethwaite Hall of Fame
Chris Parmer@chriddyp Hall of Fame
Alex Vados@alexander-daniel Hall of Fame

Copyright and license

Code and documentation copyright 2021 Plotly, Inc.

Code released under the MIT license.

Versioning

This project is maintained under the Semantic Versioning guidelines.

See the Releases section of our GitHub project for changelogs for each release version of plotly.js.


Community

  • Follow @plotlygraphs on Twitter for the latest Plotly news.
  • Implementation help may be found on community.plot.com (tagged plotly-js) or on Stack Overflow (tagged plotly).
  • Developers should use the keyword plotly on packages which modify or add to the functionality of plotly.js when distributing through npm.

Author: Plotly
Source Code: https://github.com/plotly/plotly.js 
License: MIT license

#javascript #visualization #d3 #charts #webgl 

Plotly.js: Open-source JavaScript Charting Library Behind Plotly, Dash
Nat  Grady

Nat Grady

1657111080

Disk & Memory Space Visualization App Built with Electron & D3.js

Space Radar Electron

SpaceRadar allows interactive visualization of disk space and memory. It currently supports Sunburst, Treemap, and Flamegraph charts.

Features

  • space visualizations using sunburst and treemap charts
  • previews visualization as disk is being scanned
  • fast (completes disk scanner faster than du)
  • cross platform (at least on Mac OS X and Windows)
  • allow drilldown of directories
  • breadcrumbs and navigation
  • opens files and directories
  • analyze disk contents from a remote server (see section Reading from a file)

Screenshots

space-radar-4

screenshot 2015-11-09 04 45 27

screenshot 2015-11-09 04 45 36

Reading from a file

To create a file to be read from use du -ak, for example:

  • du -ak /var/log /usr | gzip -c > /tmp/sizes.txt.gz
  • du -ak /opt /home /tmp > /tmp/sizes.txt

Compressed files can be read directly. To detect them, the file name has to end with .gz.

Future Enhancements

  • more target for scanning
  • color by file types
  • filter hidden files
  • moar!!
  • let me know what you think

Futher Explorations

  • More efficient memory usage
  • More efficient scanning process
  • 3D visualization

History

This project started as quick prototype for me to test drive electron (& some es6 syntax), d3.js and for me to explore the question of "what's taking up my disk space". Turns out writing a disk visualization app isn't that simple as I dwell into figuring out how to make disk scanning not block the ui thread, ipc calls go faster, smoother rendering, lesser memory usage, more sensible interactions...

Whats New

V5

  • Import from DU file
  • Upgrade electron
  • Flamegraphs (BETA)
  • Directory Listview
  • Update libs - Electron, D3

V4

  • Treemap view
  • Memory monitoring
  • Mac App look using Photon
  • Context Menus for locating + opening + deleting files / directories
  • Navigation controls (back/fwd/up)
  • Switched disk scanning jobs to invisible renderer process

Version 3

  • App icon finally! Thanks Jill for the help with this :)
  • Many Bug fixes
  • Disk scanning is moved to a webview process
  • Investigated various RPC methods. Now uses LocalStorage + FileSystem IPC message passing
  • Reduce memory usage (and Electron crashes) by not caching key paths
  • Tested on > 100GB & 2M files
  • Improvements to user interactivity esp on hover states
  • To prevent renderer process from hitting heap mem limit (1.5GB), all previous data is null, with dom elements removed to reduce memory pressure
  • Allow target selection for disk usage scanning
  • Locate path in Finder
  • Env Debug Flags

Version 2

  • Major speed up scanning directories. About 10x from version 1, and almost as fast or faster than du.
  • Runs disk scanning as a separate headless renderer process
  • Json is passed back via IPC
  • Remove Async npm dependency

Issues

Please raise on github issue tracker or contact @blurspline on twitter

Development

Run

npm run debug

or

npm run app

Check that dependencies are installed, otherwise run (this may take awhile for electron binaries)

npm run install

Downloads

Download Mac and Windows at the releases page

Thanks

  • Jill for designing the app logo
  • Jianwei for his comments on the app
  • Chee Aun for helping alpha test the app
  • WM for his talk on Electron that got me started
  • Contributors

Author: zz85
Source Code: https://github.com/zz85/space-radar 
License: 

#electron #d3 #visualization #javascript 

Disk & Memory Space Visualization App Built with Electron & D3.js
Reid  Rohan

Reid Rohan

1656971760

D3Snippets: A set of d3 snippets for VS code

D3.js snippets

Description

A set of snippets for Visual Studio Code helping performing some common operations with D3.js. These snippets work both with TypeScript and Javacript (ES6 /ES2015 or above).

Available Commands

All commands start with the d3 prefix

d3LinScale (v4 specific)

Creates a linear scale.

Output:

let scale = d3.scaleLinear()
    .domain([0, 1])
    .range([0,width]);

d3LinAxis (v4 specific)

Creates a linear axis in a selection.

Output:

let scale = d3.scaleLinear()
    .domain([0, 1])
    .range([0,width]);
let axis = d3.axisBottom(scale);
let axisGroup = container.append('g')
    .classed('axis', true)
    .call(axis);

d3v3LinearScale (v3 specific)

Creates a linear scale.

Output:

var scale = d3.scale.linear()
  .domain([0, 1])
  .range([0,width])

d3v3LinearAxis (v3 specific)

Creates a linear axis in a selection.

Output:

var scale = d3.scale.linear()
  .domain([0, 1])
  .range([0,width])
var axis = d3.svg.axis()
  .orient('bottom')
  .scale(scale);
var axisGroup = container.append('g')
  .classed('axis', true)
  .call(axis);

d3Transform

Appends the transform attribute in situ.

Output:

.attr('transform', (d, i) => `translate(${},${})`)

d3Rect

Appends a rectangle to a selection.

Output:

var rect = container.append('rect')
  .attr('x', )
  .attr('y', )
  .attr('width', )
  .attr('height', )
  .style('stroke','none')
  .style('fill','lightblue');

d3Circle

Appends a circle to a selection.

Output:

var circle = container.append('circle')
  .attr('cx', )
  .attr('cy', )
  .attr('r', )
  .style('stroke','none')
  .style('fill','lightblue');

d3Bind

Creates an exit-enter stub.

Output:

var dataBound = container.selectAll('.classed')
    .data(data);
dataBound
    .exit()
    .remove();
var enterSelection = dataBound
    .enter()
    .append('g')
    .classed('classed', true);

d3Csv

Creates a stub to read a csv file.

Output:

d3.csv('filename.csv',
(error, data) => {
   if (error) {
       console.error(error);
   } else {
       console.log(data);
   }
});

d3Plot

Creates an svg,and a group with margins as a container for plotting purpose.

Output:

let svg = d3.select('#chart')
    .append('svg')
    .attr('width', width)
    .attr('height', height);

let plotMargins = {
    top: 30,
    bottom: 30,
    left: 150,
    right: 30
};
let plotGroup = svg.append('g')
    .classed('plot', true)
    .attr('transform', `translate(${plotMargins.left},${plotMargins.top})`);

let plotWidth = width - plotMargins.left - plotMargins.right;
let plotHeight = height - plotMargins.top - plotMargins.bottom;

Author: Ledragon
Source Code: https://github.com/Ledragon/d3Snippets 
License: MIT license

#javascript #d3 #vscode 

D3Snippets: A set of d3 snippets for VS code
Reid  Rohan

Reid Rohan

1656964260

D3.js Snippets for Sublime Text 2

D3.js snippets for Sublime Text 2

Selections

seld3.select('')

selad3.selectAll('')

attr.attr('', )

translate.attr('transform', 'translate(' + 0 + ',' + 0 + ')')

style.style('fill', '#000')

join

d3.selectAll('')
    .data()

margin

var margin = { top: 10, right: 10, bottom: 10, left: 10 };
    width = 960 - margin.left - margin.right,
    height = 640 - margin.top - margin.bottom;

var svg = d3.select('body').append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
  .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

Data

dsvvar dsv = d3.dsv(';', 'text/plain');

csv

d3.csv('/', function(d) {
  return {

  };
}, function(err, rows) {

});

json

d3.json('/', function(err, data) {

});

SVG shapes

circle

.enter().append('circle')
    .attr('cx', )
    .attr('cy', )
    .attr('r', )
    .style('fill', '#000');

ellipse

.enter().append('ellipse')
    .attr('cx', )
    .attr('cy', )
    .attr('rx', )
    .attr('ry', )
    .style('fill', '#000');

line

.enter().append('line')
    .attr('x1', )
    .attr('y1', )
    .attr('x2', )
    .attr('y2', )
    .style('stroke', '#000');

rect

.enter().append('rect')
    .attr('x', )
    .attr('y', )
    .attr('width', )
    .attr('height', )
    .attr('rx', 0)
    .attr('ry', 0)
    .style('fill', '#000');

Geography

map

var projection = d3.geo.equirectangular()
    .center([0, 0])
    .scale(0)
    .translate([width / 2, height / 2]);

var path = d3.geo.path()
    .projection(projection);

Functions

fdfunction(d) { return ; }

fdifunction(d, i) { return ; }

fnfunction() { return ; }

Miscellaneous

scaled3.scale.linear().domain([]).range([]);

nest

var nest = d3.nest()
    .key(function(d) { return d; })
    .entries([]);

locale

var d3.locale.en_US = d3.locale({
  'decimal': '.',
  'thousands': ',',
  'grouping': [3],
  'currency': ['\$', ''],
  'dateTime': '%a %b %e %X %Y',
  'date': '%m/%d/%Y',
  'time': '%H:%M:%S',
  'periods': ['AM', 'PM'],
  'days': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  'shortDays': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  'months': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  'shortMonths': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
});

Author: Fabriciotav
Source Code: https://github.com/fabriciotav/d3-snippets-for-sublime-text-2 
License: 

#javascript #d3 #text 

D3.js Snippets for Sublime Text 2
Reid  Rohan

Reid Rohan

1656956820

D3-snippets: An Atom Package with D3v5 Snippets

d3-snippets

An Atom package with D3v5 snippets. Accelerate your graphics!

Contributions are appreciated, if you miss a snippet feel free to create an issue or open a pull request.

d3-snippets in action

Install

You can install it inside Atom (just search for d3-snippets) or via command line:

$ apm install d3-snippets

Reference

# app <>

Append something.

.append('${1:}')

# area <>

Area generator.

const area = d3.area()
    .x(d => x(d.${1:}))
    .y1(d => y(d.${2:}))
    .y0(y(0));

# attr <>

Set attributes.

.attr('${1:}', '${2:}')

# axisb <>

Bottom-oriented axis.

d3.axisBottom(${1:x});

# axisl <>

Left-oriented axis.

d3.axisLeft(${1:y});

# axisr <>

Right-oriented axis.

d3.axisRight(${1:y});

# axist <>

Top-oriented axis.

d3.axisTop(${1:x});

# axis <>

Create a SVG axis.

d3.axis()
    .scale(${1:})
    .ticks(${2:})
    .orient('${3:}')

# createblock <>

Scaffold a block.

<!DOCTYPE html>
<style>
</style>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
${1:}
</script>

# circle <>

Create a SVG circle.

.enter()
    .append('circle')
    .attr('cx', ${1:})
    .attr('cy', ${2:})
    .attr('r', ${3:})
    .style('fill', '${4:#111}');

# class <>

Set the element class.

.attr('class', '${1:}')

# csv <>

Load a CSV file.

d3.csv('${1:}').then(data => {
  ${2:console.log(data);}
});

# curve <>

Curve shorthand.

.curve(d3.${1:curveCatmullRom}.alpha(0.5));

# fdi <>

Return the data and the index.

(d, i) => ${1:}

# fd <>

Return the data.

d => ${1:}

# dom <>

Set the scale domain.

.domain([${1:}, ${2:}])

# dur <>

Set the transition duration.

.duration(${1:})

# ellipse <>

Create a SVG ellipse.

.enter().append('ellipse')
    .attr('cx', ${1:})
    .attr('cy', ${2:})
    .attr('rx', ${3:})
    .attr('ry', ${4:})
    .style('fill', '${5:#111}');

# ent <>

Enter the data.

.enter()

# extent <>

Set the dataset extent.

d3.extent(${1:data}, d => d.${2:value});

# fill-opacity <>

Set the element fill opacity.

.attr('fill-opacity', ${1:0.5})

# fill <>

Set the element fill.

.attr('fill', '${1:none}')

# fn <>

Blank anonymous function.

() => ${1:}

# geomap <>

Create the projection and path for a map.

const projection = d3.${1:geoMercator}()
    .fitSize([${2:width}, ${3:height}], ${4:land});

const path = d3.geoPath()
    .projection(projection);
${7:}

# g <>

Create a SVG group.

svg
    .append('g')
    .attr('class', '${1:}')

# join <>

Start with a data join.

d3.selectAll('${1:}')
    .data(${2:})

# json <>

Load a JSON file.

d3.json('${1:}').then(data => {
  ${2:console.log(data);}
});

# lineg <>

Line generator.

const line = d3.line()
  .x(d => x(d.${1:}))
  .y(d => y(d.${2:}));

# line <>

Create a SVG Line.

.enter().append('line')
    .attr('x1', ${1:})
    .attr('y1', ${2:})
    .attr('x2', ${3:})
    .attr('y2', ${4:})
    .style('stroke', '${5:#111}');

# locale <>

Set a default locale.

const ${1:en_US} = {
    'decimal': '.',
    'thousands': ',',
    'grouping': [3],
    'currency': ['$', ''],
    'dateTime': '%a %b %e %X %Y',
    'date': '%m/%d/%Y',
    'time': '%H:%M:%S',
    'periods': ['AM', 'PM'],
    'days': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    'shortDays': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    'months': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    'shortMonths': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
}

formatDefaultLocale(${2:en_US});
timeFormatDefaultLocale(${3:en_US});

# margin <>

Append a SVG with the margin convention.

const margin = {top: ${1:20}, right: ${2:10}, bottom: ${3:20}, left: ${4:10}},
    width = ${5:960} - margin.left - margin.right,
    height = ${6:500} - margin.top - margin.bottom;

const svg = d3.select('${7:body}').append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
  .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

${8:}

# max <>

Get the maximum value.

d3.max(${1:data}, d => d.${2:value});

# min <>

Get the minimum value.

d3.min(${1:data}, d => d.${2:value});

# nest <>

Nest a dataset.

const nest = d3.nest()
    .key(d => d.${1:})
    .entries(${2:});

# on <>

Listen for events on the selection.

.on('${1:}', ${2:})

# queue-promise <>

Load multiple files using a Promise.

Promise.all([
    d3.${1:json}('${2:}'),
    d3.${3:json}('${4:}')
  ]).then([${5:file1}, ${6:file2}] => {
    console.log(${7:file1}, ${8:file1});
  })

# queue <>

Create a queue to load multiple files.

d3.queue()
    .defer(${1:d3.json}, '${2:}')
    .defer(${3:d3.json}, '${4:}')
    .await(function(error, ${5:file1}, ${6:file2}) {
        console.log(${7:file1}, ${8:file1});
    });

# r <>

Set the element radius.

.attr('r', ${1:5})

# ran <>

Set the scale range.

.range([${1:}, ${2:}])

# rect <>

Create a SVG rect.

.enter().append('rect')
    .attr('x', ${1:})
    .attr('y', ${2:})
    .attr('width', ${3:width})
    .attr('height', ${4:height})
    .attr('rx', ${5:0})
    .attr('ry', ${6:0})
    .style('fill', '${7:#111}');

# seq <>

Create a sequential scale.

d3.scaleSequential(d3.${1:interpolateViridis})
    .domain([${2:}])

# scale <>

Create a sample scale.

d3.${1:scaleLinear}()
    .domain([${2:}, ${3:}])
    .range([${4:}, ${5:}]);

# sel <>

Select an element.

d3.select('${1:}')

# sela <>

Select all the elements.

d3.selectAll('${1:}')

# sort <>

Sort a dataset.

${1:data}.sort((a, b) => ${2:a}.${3:value} - ${4:b}.${5:value});

# stroke-opacity <>

Set the element stroke opacity.

.attr('stroke-opacity', ${1:0.5})

# stroke-width <>

Set the element stroke width.

.attr('stroke-width', ${1:1})

# stroke <>

Set the element stroke.

.attr('stroke', '${1:black}')

# style <>

Set the element style.

.style('${1:}', '${2:}')

# anchor <>

Set the text anchor.

.attr('text-anchor', '${1:middle}')

# text <>

Set the element text.

.text('${1:}')

# tickSize <>

Set the tick size.

.tickSize(${1:})

# tickValues <>

Set the tick values.

.tickValues(['${1:}'])

# translate <>

Translate the element.

.attr('transform', `translate(${${1:0}},${${2:0}})`)

# voronoi <>

Create a Voronoi diagram.

const voronoi = d3.voronoi()
    .x(d => x(d.${1:}))
    .y(d => y(d.${2:}))
    .extent([[0, 0], [${3:width}, ${4:height}]]);

const voronoiGroup = svg.append('g')
    .attr('class', 'voronoi');

voronoiGroup.selectAll('path')
    .data(voronoi.polygons(${5:data}))
    .enter().append('path')
    .attr('d', d => d ? 'M' + d.join('L') + 'Z' : null)

# x <>

Set the x position.

.attr('x', ${1:})

# y <>

Set the y position.

.attr('y', ${1:})

Hacking

$ cd ~/.atom/packages
$ git clone git@github.com:martgnz/d3-snippets.git
$ cd d3-snippets
$ apm install
$ apm link

Credit

Most of the inspiration comes from fabriotav's and shancarter's Sublime Text packages.

Author: Martgnz
Source Code: https://github.com/martgnz/d3-snippets 
License: MIT license

#javascript #d3 #graphic 

D3-snippets: An Atom Package with D3v5 Snippets
Reid  Rohan

Reid Rohan

1656949403

Kyrix: Interactive Details-on-demand Data Visualizations At Scale

Kyrix - democratizing details-on-demand data visualizations

Kyrix facilitates the creation of data visualizations with details-on-demand interactions (e.g. pan and zoom, see the demo gallery1 above). In visualizations of such, the underlying dataset is often large. To deal with large data, Kyrix is focused on optimizing two goals: 1) usable declarative API library for visualization developers and 2) 500ms response time to user interactions, which is required to enable interactive browsing.

  1. This gallery GIF is itself a Kyrix application.

Installation instructions for the impatient

  1. Install Docker and Docker Compose (must be v1.17.0 or later). For Mac users, installing Docker Desktop will install Docker Compose automatically. Ubuntu 18.04 users can also simply install with sudo apt update; sudo apt install -y docker.io docker-compose;.
  2. Run sudo ./run-kyrix.sh --nba --build in the root directory. You might need to make run-kyrix.sh executable, i.e. sudo chmod +x run-kyrix.sh.
  3. Wait a couple minutes, then point your browser at <ip address>:8000 - remember that if you are using a cloud instance you may (probably) need to open your cloud provider's firewall for this port. If that sounds scary, you can create an SSH tunnel from your PC (e.g. Mac) using ssh -N <server ipaddr> -L 8000:<same ipaddr>:8000 to forward your laptop's port 8000 to the server via SSH tunneling.

note that you'll need to wait for a message saying Backend server started... like this:

Serving /project
New project definition coming...
There is diff that requires recomputing indexes. Shutting down server and recomputing...
Precomputing...
Done precomputing!
Completed recomputing indexes. Server restarting...
Backend server started...
*** done! Kyrix ready at: http://<host>:8000/

Getting started by reading a tutorial, and more documentations.

Setup-free big data visualizations

Kyrix is fully dockerized, with a live PostgreSQL database running right after docker startup. Front-end vis libraries often assume data fits in browser memory, and thus scale to only small data. By working with a containerized database, Kyrix scales to much larger data while being free of the hassle of installing and maintaining databases.

Docker works by creating fully isolated virtual machines ("containers") on your computer, making it much easier to achieve correct installations every time (learn more). See docker config details.

Declarative authoring

Kyrix offers two declarative grammars for authoring complex details-on-demand visualizations. Low-level Kyrix grammar is verbose but expressive. Kyrix-S grammar is a high-level and concise grammar designed for zoomable scatterplot visualizations. For example, Kyrix-S turns

{
    data: {  
        db: "nba",  
        query: “SELECT * FROM games"  
    },  
    layout: {  
        x: {  
            field: "home_score",  
            extent: [69, 149]  
        },  
        y: {  
            field: "away_score",  
            extent: [69, 148]  
        },  
        z: {  
            field: "agg_rank",  
            order: "asc"  
        }  
    },  
    marks: {  
        cluster: {  
            mode: "circle"
        },  
        hover: {  
            rankList: {  
                mode: "tabular",  
                fields: ["home_team", "away_team", "home_score", "away_score"],  
                topk: 3  
            },  
            boundary: "convexhull"  
         }  
    },  
    config: {  
        axis: true  
    }  
};

into

 

Embedding into your favourite web app

Kyrix offers APIs to integrate a kyrix application into a web application. There's no limit on what you can imagine: complex coordinated views, programmatic pan/zoom control, cross filtering...

Telling us about your Kyrix app

We'd like to learn more about your application requirements to make Kyrix better. If you have built a Kyrix app, send us a screenshot on Gitter!

Disclaimer

The current v1.0.0-beta release contains research-quality code, and is intended for demo purposes. The code should not be used for large-scale secure serving. Currently, v1.0.0-beta only supports data with up to 10~100 millions of data records. We plan to release a distributed version of Kyrix in the future.

Citing Kyrix

@inproceedings{tao2019kyrix,
  title={Kyrix: Interactive pan/zoom visualizations at scale},
  author={Tao, Wenbo and Liu, Xiaoyu and Wang, Yedi and Battle, Leilani and Demiralp, {\c{C}}a{\u{g}}atay and Chang, Remco and Stonebraker, Michael},
  booktitle={Computer Graphics Forum},
  volume={38},
  number={3},
  pages={529--540},
  year={2019},
  organization={Wiley Online Library}
}

Author: Tracyhenry
Source Code: https://github.com/tracyhenry/Kyrix 
License: MIT license

#javascript #d3 #datavisualization 

Kyrix: Interactive Details-on-demand Data Visualizations At Scale
Reid  Rohan

Reid Rohan

1656941949

D3-node: Server-side D3 for Static Chart/map Generation

D3-Node

Server-side D3 with ease  

Tested on Nodejs v10 & up

maps and charts with d3-node

see examples >

js-standard-style

Why?

Basic usage:

NPM

Create a SVG

 const D3Node = require('d3-node')
 const d3n = new D3Node()      // initializes D3 with container element
 d3n.createSVG(10,20).append('g') // create SVG w/ 'g' tag and width/height
 d3n.svgString() // output: <svg width=10 height=20 xmlns="http://www.w3.org/2000/svg"><g></g></svg>

Advanced usage

Setting container & insertion point via selector

 const options = { selector: '#chart', container: '<div id="container"><div id="chart"></div></div>' }
 const d3n = new D3Node(options) // initializes D3 with container element
 const d3 = d3n.d3
 d3.select(d3n.document.querySelector('#chart')).append('span') // insert span tag into #chart
 d3n.html()   // output: <html><body><div id="container"><div id="chart"><span></span></div></div></body></html>
 d3n.chartHTML()   // output: <div id="chart"><span></span></div>

Inline SVG styles

 const d3n = new D3Node({styles:'.test {fill:#000;}'})
 d3n.createSVG().append('g')
 d3n.svgString()

Output

<svg xmlns="http://www.w3.org/2000/svg">
   <defs>
     <style type="text/css"><![CDATA[ .test{fill:#000;} ]]></style>
   </defs>
   <g></g>
<svg>

Create a canvas (for generating a png)

 const canvasModule = require('canvas'); // supports node-canvas v1 & v2.x
 const d3n = new D3Node({ canvasModule }); // pass it node-canvas
 const canvas = d3n.createCanvas(960, 500);
 const context = canvas.getContext('2d');
 // draw on your canvas, then output canvas to png
 canvas.pngStream().pipe(fs.createWriteStream('output.png'));

See examples for more...

Run Tests:

$ npm test

TODOs:

  • Add more examples: (remote data, world map)
  • Create Gulp task
  • Add option to inject css/js into html output

Author: d3-node
Source Code: https://github.com/d3-node/d3-node 
License: 

#javascript #d3 #node #datavisualization 

D3-node: Server-side D3 for Static Chart/map Generation
Reid  Rohan

Reid Rohan

1656934391

Twitter Sentiment Visualisations

Twitter Sentiment Visualisations

A web app that uses data from Twitter combined with sentiment analysis and emotion detection to create a series of data visualisations to illustrate the happy and less happy locations, topics and times.

Introduction

This project aims to make Twitter data more understandable. It streams real-time tweets, or can fetch tweets about a specific topic or keyword - it then analyses this data using a custom-written sentiment analysis algorithm, and finally displays the results with a series of dynamic D3.js data visualisations.

The aim of the app is to allow trends to be found between sentiment and other factors such as geographical location, time of day, other topics...

It has a wide range of uses, from analysing the effectiveness of a marketing campaign, to comparing two competing topics.

Screen Shots

As part of the documentation there is one shot of each screen in it's current state. View screen shots here

Below is a sample of the 12 key screens. Overview of screenshots

Modules

Several open source node modules have been developed and published on npm as part of this project

Project Planning

Running Locally

Prerequisites - You will need Node.js, MongoDB and git installed on your system. You will also need Gulp and Bower, which (once node is installed) you can install by running npm install gulp bower -g. Also Yarn is recommended.

Get the files - git clone https://github.com/Lissy93/twitter- sentiment-visualisation.git then navigate into it with cd twitter-sentiment-visualisation

Install dependencies - yarn will install the npm node_modules, then should automatically kick off a bower install (if not, then just run it manually). If you are developing, you will need to use npm install in order to get the devDependencies too.

Set Config yarn run config will generate the config\src\keys.coffee file, which you will then need to populate with your API keys and save. Also check that your happy with the general app config in config/src/app-config.coffee.

Build Project - yarn run build will compile the project, from the source.

Start MongoDB - mongod will start a MongoDB instance (run in separate terminal instance). See instructions: Starting a MongoDB instance.

Run the project - Run yarn start then open your browser and navigate to http://localhost:8080

View detailed installation instructions

To run the tests: npm test or see the more test strategy

To run in development mode, use yarn run dev. This will use dev environmental variables, and also will watch for changes, lint, compile and refresh automatically.

Automated Development Workflow

TSV uses the Gulp streaming build tool to automate the development workflow.

The key tasks you need to run are:

  • gulp generate-config - before first-time running of the project, run this command to generate configuration files for your API keys
  • gulp build - This will build the project fully, this includes cleaning the working directory and then all tasks that must happen for CoffeeScript, JavaScript, CSS, images, HTML and Browserify tasks.
  • gulp nodemon - Runs the application on the default port (probably 8080)
  • gulp test - This will run all unit and coverage tests, printing a summary of the results to the console and generating more detailed reports into the reports directory.
  • gulp - this is the default task, it will check the project is configured correctly, build ALL the files, run the server, watch for changes, recompile relevant files and reload browsers on change, and keep all browsers in sync, when a test condition changes it will also re-run tests - a lot going on!

To read more about the project setup and gulp process, see build environment in the docs

Test Strategy

Twitter Sentiment Visualisation follows the TDD approach and is structured around it's unit tests.

To run tests: npm test

Testing Tools

More details on each of the tools and how they will be implemented along with the pass and fail criteria can be found on the test strategy page of the documentation.

The Stack

This project wouldn't have been possible at all without making use of many many open source packages, libraries, frameworks etc..

I would like to personally thank the hundreds of developers who have worked on open source packages like these.

There is an extensive stack of technologies that were used to develop the final application. The following list is a summary of the key utilities:

The Stack

Documentation

Project Information

Project Introduction

Addressing Potential Risks

System Development Life Cycle

Licence


Project Planning

User Stories

Complexity Estimates

High Level UML

Methodology - frontend

Test Strategy


Development Documentation

Installation Instructions

Build Environment

Testing


Research

The current sentiment analysis scene

Comparison of various sentiment analysis algorithm approaches

References


Read more about the application here.

The application is fully documented, which can be viewed here

Live Application

A live demo of the application has been deployed to: http://sentiment-sweep.com

Author: Lissy93
Source Code: https://github.com/Lissy93/twitter-sentiment-visualisation 
License: 

#javascript #d3 #datavisualisation 

Twitter Sentiment Visualisations
Reid  Rohan

Reid Rohan

1656926760

Treeviz: Tree Diagrams with JavaScript

Treeviz

This javascript module aims at providing an easy interface in order to represent tree diagrams on screen with the ability to handle dynamic data flows. The data format must be JSON.

💅 Come play with the Treeviz storybook! 💅

Installation

With npm : npm install treeviz

and then you can use it with : import * as Treeviz from 'treeviz';

Or download this repository and link the dist/index.js file in your page directly : <script src="./dist/index.js><script> Also, but not recommended, you can use : <script src="https://rawgit.com/PierreCapo/treeviz/master/dist/index.js"></script>

Usage

React

Check the treeviz wrapper for react: treeviz-react

Vanilla JavaScript

// Define a tree element where dimensions are mandatory
<div id="tree" style="height:700px; width:900px"></div>

<script>
// Define a dataset
var data = [
  { id: 1, text_1: "Father", father: null },
  { id: 2, text_1: "Child A", father: 1 },
  { id: 3, text_1: "Child B", father: 1 },
  { id: 4, text_1: "Subchild C", father: 2 }
];

// Define and configure a tree object
var myTree = Treeviz.create({
  htmlId: "tree",
  idKey: "id",
  hasFlatData: true,
  nodeColor: (nodeData) => "grey",
  relationnalField: "father",
});

// Display the tree based on the data
myTree.refresh(data);
</script>

To update the tree visually you will just have to pass new data to the refresh method like this :

myTree.refresh(data);
myTree.refresh(data_update1);
myTree.refresh(data_update2);

The tree will be clever enough to updates only the part of the trees that have been added or removed in the dataset, and so it won't redraw the entire tree.

Treeviz Example

Hierarchical data case :

var hierarchical_data_example = {
  name: "Mom",
  qty: 10,
  children: [
    { name: "Son A", qty: 3 },
    { name: "Son B", qty: 7 },
  ],
};

var myTree = Treeviz.create({
  htmlId: "tree",
  idKey: "name",
  hasFlatData: false,
  relationnalField: "children",
});

myTree.refresh(hierarchical_data_example);

API

The big part of the API is configuring the tree before passing data to it :

Treeviz.create(config);

The table below lists all the avalaible key that the config object can have

KeyTypeDefaultDefinition
htmlIdstring (Required) The HTML id tag on the page where the tree should be drawn. It must have a width and an height specified
idKeystring"id"The key in a data item representing the unique identifier of a node
relationnalFieldstring"father"In case of flat dataset, usually the relationnal field between each node is the field representing the father of the node, linking it to the id of the field. (See example below).
hasFlatDatabooleantrueSpecify whether the data passed to the tree is flat or already hierarchical
hasPanbooleanfalseToggle the ability to pan the tree
hasZoombooleanfalseToggle the ability to zoom the tree
nodeWidthnumber160Width of a node in px
nodeHeightnumber100Height of a node in px
linkColorfunction(nodeData) => "#ffcc80"Color of the link
linkWidthfunction(nodeData) => 10Width of the link
linkShape"quadraticBeziers" | "orthogonal" | "curve""quadraticBeziers"Shape of the link
renderNodefunction(nodeData) => nullHTML template for every node
isHorizontalbooleantrueDirection of the tree. If true, the tree expands from left to right. If false, it goes from top to bottom
onNodeClickfunction(nodeData) => nullFunction handling the event when someone click on it
onNodeMouseEnterfunction(nodeData) => nullFunction handling the event when someone hover a node
onNodeMouseLeavefunction(nodeData) => nullFunction handling the event when the mouse pointer leaves a node
mainAxisNodeSpacingnumber or "auto"300Set the distance in pixels between two depths in the tree. If the value is auto it will automatically display the tree to fit the size of the container.
secondaryAxisNodeSpacingnumber1.25Set the distance between nodes in the same level as a coefficient of node dimensions. Recommended to have the value superior to 1
marginTopnumber1.25Set the margin between the SVG element and the tree
marginBottomnumber1.25Set the margin between the SVG element and the tree
marginLeftnumber1.25Set the margin between the SVG element and the tree
marginRightnumber1.25Set the margin between the SVG element and the tree
durationnumber600The duration of the animation transition between layouts

Credits

This module is based on d3 library, credit to all the contributors of this project.

Author: PierreCapo
Source Code: https://github.com/PierreCapo/treeviz 
License: BSD

#javascript #visualization #d3 #tree 

Treeviz: Tree Diagrams with JavaScript
Reid  Rohan

Reid Rohan

1656919208

Netvis: D3.js-based tool To Visualize Network Communication

NetVis

NetVis is a highly customizable javascript framework for building interactive network visualizations:

Visualize any network activity by describing your network events in a straightforward JSON-based NetVis format detailing network nodes, events and messages.

Convert your server logs / network trace files to NetVis format and quickly visualize them. Generic nature of the tool means support for visualizing communication in any existing protocols, including IP, TCP, HTTP, TSL, BitCoin or IPFS as well as a pefrect tool for developing new network protocols.

Browse and traverse your network model with the d3-based graph visualization and time playback controls (play/pause/ffwd/rwind/speed) for events.

Customize the looks and appearance easily by overwriting the default View handlers in plain javascript. NetVis maintains the form and function customization separate. Specifying custom colors and tags for nodes and messages, or things like depicting the nodes on the georgaphical map is super simple.

NetVis is built by the IPFS (ipfs.io, github.com/jbenet/ipfs) and Filecoin (filecoin.io) team.

What can NetVis do for me?

Here is an example of the use case:

  1. Live nodes implementing protocols run, generating a real sequence of events. They store this sequence in one or many log files.
  2. The log files are consolidated into one netvis history.
  3. The history is fed into a simulator, which runs the visualization.

This means that the live nodes / producers need not emit netvis exactly; we can have a processing step in the pipeline that converts whatever the native protocol logs are into netvis. (for example, combining two differet entries, announcing an outgoing + incoming packet, into one single netvis message entry)

And it also means that simulators need not ingest netvis directly, but can also be processed to fit their purposes better. This makes netvis a middle-format that seeks to ensure all the necessary elements are present, and that both the producer and consumer programs handle them correctly.

netvis pipeline:

live nodes --> logs --> netvis logs --> simulator input --> simulator

NetVis format

See the specififcation draft.

Here is an example of a NetVis file:

  [
    {
      "time": "2014-11-12T11:34:01.077817100Z",
      "loggerID":"QmdqaPCyuyAD2DNGGVTEdUmH33sBF62YpSM7oWi1CoCkm8",
      "level": "info",
      "event":"nodeEntered",
      "name": "Earth"
    },

    {
      "time": "2014-11-12T11:34:01.477817180Z",
      "loggerID":"QmdqaPCyuyAD2DNGGVTEdUmH33sBF62YpSM7oWi1CoCkm8",
      "level": "info",
      "event":"messageSent",
      "destinationNode": "Qmd9uGaZ6vKTES5nezVyCZDP2zJzdii2EXWiCbyGYq1tZX",
      "message":
      {
          "request_id": "c655d844aed528caabfad155408ee5832ba64d78",
          "time": "2014-11-12T11:34:01.477817180Z",
          "protocol": "IPFS 0.1",
          "type": "join",
          "contents": "{\"body\":\"Hello Jupiter!This is Earth, bow to our might!\"}"
      }
    },

    {
      "time": "2014-11-12T11:34:02.000000003Z",
      "loggerID":"QmdqaPCyuyAD2DNGGVTEdUmH33sBF62YpSM7oWi1CoCkm8",
      "level": "info",
      "event":"messageReceived",
      "sourceNode": "Qmd9uGaZ6vKTES5nezVyCZDP2zJzdii2EXWiCbyGYq1tZX",
      "message":
      {
          "request_id": "a001c4d79b323808729ecfe673d84048e1725b39a96049dce2241dbd11d6abf9",
          "time": "2014-11-12T11:34:01.900000003Z",
          "protocol": "IPFS 0.1",
          "type": "lol",
          "contents": "lol wat"
      }
    }
  ]

We see an example of simple network activity where a node "Earth" sends a message to "Jupiter" and get a response.

Note that while the Earth node is defined with a nodeEntered event, Jupiter is only introduced implicitely, by being mentioned. That is acceptable, NetVis tries to deduce things as much as possible.

Other

Also see:

  • DESIGNDOC.md - netvis project design and API doc
  • netvis.md netvis network log file format specification
  • ROADMAP.md, project development roadmap
  • DEVELOPING.md, internal designdoc. If you are considering contributing, or just want to see how things work internally, awesome! That would be a good place to start.

( good place to start is the showcasing page.)

Author: dborzov
Source Code: https://github.com/dborzov/netvis 
License: MIT license

#javascript #d3 #network #protocol 

Netvis: D3.js-based tool To Visualize Network Communication