import json file to create a network in vis.js - javascript

I am using vis.js to create a mapping, I using file saveAndLoad.html in the example code. The save function is good, I can export json file. But when I load the json file in import function it doesn't create a mapping for me. I don't know what is my misunderstanding please help. this is the import function.
function importNetwork() {
/*var inputValue = exportArea.value;
var inputData = JSON.parse(inputValue);
var data = {
nodes: getNodeData(inputData),
edges: getEdgeData(inputData)
}
network = new vis.Network(container, data, {});*/
var gephiJSON = loadJSON("./1.json"); // code in importing_from_gephi.
// you can customize the result like with these options. These are explained below.
// These are the default options.
var parserOptions = {
edges: {
inheritColors: false
},
nodes: {
fixed: true,
parseColor: false
}
}
// parse the gephi file to receive an object
// containing nodes and edges in vis format.
var parsed = vis.network.convertGephi(gephiJSON, parserOptions);
// provide data in the normal fashion
var data = {
nodes: parsed.nodes,
edged: parsed.edges
};
// create a network
var network = new vis.Network(container, data);
resizeExportArea();
}

I searched quite a bit for a solution to the obstensively simple task of loading an external JSON datafile into a vis.js Network. Here is a working solution.
Read my comments in the HTML file (below), for more information:
I installed vis.js via NPM, but you can also just download / source the vis.min.js file;
The code provided by visjs.org in the "full options" tab for the Network module edge options was buggy, due to extra commas, etc. I included a working copy in my HTML code (ditto re: the "physics" options).
As noted in the comments in my HTML file, the formatting of the JSON datafile is very particular: use double quotation marks; curly braces { } are not quoted (e.g., if you want to define per-edge attributes, in that file); ....
json_test.html
<!doctype html>
<HTML>
<HEAD>
<meta charset="utf-8" />
<TITLE>[vis.js] Network | Basic Usage | TEST: Load External JSON Datafile</TITLE>
<!-- NPM (http://visjs.org/index.html#download_install): -->
<!-- <script type="text/javascript" src="node_modules/vis/dist/vis.min.js"></script> -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
<!-- Needed for JSON file import (https://stackoverflow.com/questions/33392557/vis-js-simple-example-edges-do-not-show): -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- http://visjs.org/index.html#download_install -->
<!-- <link rel="stylesheet" type="text/css" href="node_modules/vis/dist/vis.css"> -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css">
<style type="text/css">
#mynetwork {
/* width: 600px; */
width: 100%;
height: 800px;
border: 2px solid lightgray;
}
</style>
</HEAD>
<BODY>
<div id="mynetwork"></div>
<!-- Add an invisible <div> element to the document, to hold the JSON data: -->
<div id="networkJSON-results" class="results" style="display:none"></div>
<script type="text/javascript">
// -------------------------------------------------------------------------
// OPTIONS:
// http://visjs.org/docs/network/#modules
// http://visjs.org/docs/network/edges.html#
// http://visjs.org/docs/network/physics.html#
var options = {
edges: {
arrows: {
to: {enabled: true, scaleFactor:0.75, type:'arrow'},
// to: {enabled: false, scaleFactor:0.5, type:'bar'},
middle: {enabled: false, scalefactor:1, type:'arrow'},
from: {enabled: true, scaleFactor:0.3, type:'arrow'}
// from: {enabled: false, scaleFactor:0.5, type:'arrow'}
},
arrowStrikethrough: true,
chosen: true,
color: {
// color:'#848484',
color:'red',
highlight:'#848484',
hover: '#848484',
inherit: 'from',
opacity:1.0
},
dashes: false,
font: {
color: '#343434',
size: 14, // px
face: 'arial',
background: 'none',
strokeWidth: 2, // px
strokeColor: '#ffffff',
align: 'horizontal',
multi: false,
vadjust: 0,
bold: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'bold'
},
ital: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'italic'
},
boldital: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'bold italic'
},
mono: {
color: '#343434',
size: 15, // px
face: 'courier new',
vadjust: 2,
mod: ''
}
}
},
// http://visjs.org/docs/network/physics.html#
physics: {
enabled: true,
barnesHut: {
gravitationalConstant: -2000,
centralGravity: 0.3,
// springLength: 95,
springLength: 175,
springConstant: 0.04,
damping: 0.09,
avoidOverlap: 0
},
forceAtlas2Based: {
gravitationalConstant: -50,
centralGravity: 0.01,
springConstant: 0.08,
springLength: 100,
damping: 0.4,
avoidOverlap: 0
},
repulsion: {
centralGravity: 0.2,
springLength: 200,
springConstant: 0.05,
nodeDistance: 100,
damping: 0.09
},
hierarchicalRepulsion: {
centralGravity: 0.0,
springLength: 100,
springConstant: 0.01,
nodeDistance: 120,
damping: 0.09
},
maxVelocity: 50,
minVelocity: 0.1,
solver: 'barnesHut',
stabilization: {
enabled: true,
iterations: 1000,
updateInterval: 100,
onlyDynamicEdges: false,
fit: true
},
timestep: 0.5,
adaptiveTimestep: true
},
};
// -------------------------------------------------------------------------
// IMPORT DATA FROM EXTERNAL JSON FILE:
// Per: https://github.com/ikwattro/blog/blob/master/sources/easy-graph-visualization-with-vis-dot-js.adoc:
// NOTES:
// 1. Must use double quotes ("; not ') in that JSON file;
// 2. Cannot have comments in that file, only data! See:
// https://stackoverflow.com/questions/244777/can-comments-be-used-in-json
// 3. Per the path below, place the "test.json" file in a "data" subdirectory.
var json = $.getJSON("data/test.json")
.done(function(data){
var data = {
nodes: data.nodes,
edges: data.edges
};
var network = new vis.Network(container, data, options);
});
var container = document.getElementById('mynetwork');
</script>
</BODY>
</HTML>
test.json
{"nodes":[
{"id":"1", "label":"Node 1"}
,{"id":"2", "label":"Node 2\nline 2"}
,{"id":"3", "label":"Node 3"}
,{"id":"4", "label":"Node 4"}
,{"id":"5", "label":"Node 5"}
],
"edges":[
{"from":"1", "to":"2", "label":"apples"}
,{"from":"1", "to":"3", "label":"bananas"}
,{"from":"2", "to":"4", "label":"cherries"}
,{"from":"2", "to":"5", "label":"dates"}
,{"from":"2", "to":"3", "label":"EAGLES!", "color":{"color":"green", "highlight":"blue"}, "arrows":{"to":{"scaleFactor":"1.25", "type":"circle"}}}
]
}
Output

Related

Using vis.js to populate nodes and links from json file

I running basic html and json file to visualize nodes and links using vis.js. Json files contain list of nodes and links/edges. I refer to SO sample here to run it... example . I test using the examples and it does work and show all the nodes and links. I replace the json file with my own data and when i execute the code... it just show the nodes without any link.
My Json file
{
"nodes": [
{
"id": "openflow:1",
"tpid": [
"openflow:1:2",
"openflow:1:1",
"openflow:1:LOCAL"
]
},
{
"id": "host:00:00:00:00:00:01",
"ip": "10.0.0.1",
"mac": "00:00:00:00:00:01",
"tpid": [
"host:00:00:00:00:00:01"
]
},
{
"id": "openflow:2",
"tpid": [
"openflow:2:LOCAL",
"openflow:2:1",
"openflow:2:2"
]
},
{
"id": "host:00:00:00:00:00:02",
"ip": "10.0.0.2",
"mac": "00:00:00:00:00:02",
"tpid": [
"host:00:00:00:00:00:02"
]
}
],
"edges": [
{
"id": "host:00:00:00:00:00:01/openflow:1:1",
"source": "host:00:00:00:00:00:01",
"target": "openflow:1:1"
},
{
"id": "openflow:2:1/host:00:00:00:00:00:02",
"source": "openflow:2:1",
"target": "host:00:00:00:00:00:02"
},
{
"id": "openflow:1:2",
"source": "openflow:1:2",
"target": "openflow:2:2"
},
{
"id": "openflow:2:2",
"source": "openflow:2:2",
"target": "openflow:1:2"
},
{
"id": "openflow:1:1/host:00:00:00:00:00:01",
"source": "openflow:1:1",
"target": "host:00:00:00:00:00:01"
},
{
"id": "host:00:00:00:00:00:02/openflow:2:1",
"source": "host:00:00:00:00:00:02",
"target": "openflow:2:1", "color":{"color":"green", "highlight":"blue"}, "arrows":{"target":{"scaleFactor":"1.25", "type":"circle"}}
}
]
}
This is the html file
i<!doctype html>
<HTML>
<HEAD>
<meta charset="utf-8" />
<TITLE>[vis.js] Network | Basic Usage | TEST: Load External JSON Datafile</TITLE>
<!-- NPM (http://visjs.org/index.html#download_install): -->
<!-- <script type="text/javascript" src="node_modules/vis/dist/vis.min.js"></script> -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
<!-- Needed for JSON file import (https://stackoverflow.com/questions/33392557/vis-js-simple-example-edges-do-not-show): -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- http://visjs.org/index.html#download_install -->
<!-- <link rel="stylesheet" type="text/css" href="node_modules/vis/dist/vis.css"> -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css">
<style type="text/css">
#mynetwork {
/* width: 600px; */
width: 100%;
height: 800px;
border: 2px solid lightgray;
}
</style>
</HEAD>
<BODY>
<div id="mynetwork"></div>
<!-- Add an invisible <div> element to the document, to hold the JSON data: -->
<div id="networkJSON-results" class="results" style="display:none"></div>
<script type="text/javascript">
// -------------------------------------------------------------------------
// OPTIONS:
// http://visjs.org/docs/network/#modules
// http://visjs.org/docs/network/edges.html#
// http://visjs.org/docs/network/physics.html#
var options = {
edges: {
arrows: {
target: {enabled: true, scaleFactor:0.75, type:'arrow'},
// to: {enabled: false, scaleFactor:0.5, type:'bar'},
middle: {enabled: false, scalefactor:1, type:'arrow'},
source: {enabled: true, scaleFactor:0.3, type:'arrow'}
// from: {enabled: false, scaleFactor:0.5, type:'arrow'}
},
arrowStrikethrough: true,
chosen: true,
color: {
// color:'#848484',
color:'red',
highlight:'#848484',
hover: '#848484',
inherit: 'from',
opacity:1.0
},
dashes: false,
font: {
color: '#343434',
size: 14, // px
face: 'arial',
background: 'none',
strokeWidth: 2, // px
strokeColor: '#ffffff',
align: 'horizontal',
multi: false,
vadjust: 0,
bold: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'bold'
},
ital: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'italic'
},
boldital: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'bold italic'
},
mono: {
color: '#343434',
size: 15, // px
face: 'courier new',
vadjust: 2,
mod: ''
}
}
},
// http://visjs.org/docs/network/physics.html#
physics: {
enabled: true,
barnesHut: {
gravitationalConstant: -2000,
centralGravity: 0.3,
// springLength: 95,
springLength: 175,
springConstant: 0.04,
damping: 0.09,
avoidOverlap: 0
},
forceAtlas2Based: {
gravitationalConstant: -50,
centralGravity: 0.01,
springConstant: 0.08,
springLength: 100,
damping: 0.4,
avoidOverlap: 0
},
repulsion: {
centralGravity: 0.2,
springLength: 200,
springConstant: 0.05,
nodeDistance: 100,
damping: 0.09
},
hierarchicalRepulsion: {
centralGravity: 0.0,
springLength: 100,
springConstant: 0.01,
nodeDistance: 120,
damping: 0.09
},
maxVelocity: 50,
minVelocity: 0.1,
solver: 'barnesHut',
stabilization: {
enabled: true,
iterations: 1000,
updateInterval: 100,
onlyDynamicEdges: false,
fit: true
},
timestep: 0.5,
adaptiveTimestep: true
},
};
// -------------------------------------------------------------------------
// IMPORT DATA FROM EXTERNAL JSON FILE:
// Per: https://github.com/ikwattro/blog/blob/master/sources/easy-graph-visualization-with-vis-dot-js.adoc:
// NOTES:
// 1. Must use double quotes ("; not ') in that JSON file;
// 2. Cannot have comments in that file, only data! See:
// https://stackoverflow.com/questions/244777/can-comments-be-used-in-json
// 3. Per the path below, place the "test.json" file in a "data" subdirectory.
var json = $.getJSON("data/11-test2.json")
.done(function(data){
var data = {
nodes: data.nodes,
edges: data.edges
};
var network = new vis.Network(container, data, options);
});
var container = document.getElementById('mynetwork');
</script>
</BODY>
</HTML>
The output only nodes without links/edges
I have check it few times but couldn't find the bottleneck... appreciate someone to advise..what could be wrong here... Thanks
22/11/19-
Appreciate someone who knows about this problem... I have edit my json file and change source/target --> to/from and still the same...link not visible...
*23/11/19-
Still not clue to resolve the problem. Thanks for your advises.
as you say edges are not structured as { id, source, target } but as { id, from, to }. The same applies to options.edges.arrows.
This also seems problematic (two variables named data in the same scope, more like bad practice though):
.done(function(data){
var data = {
nodes: data.nodes,
edges: data.edges
};
The actual answer to your question is that you connect edges to nodes you don't have. For example the first edge goes from host:00:00:00:00:00:01 to openflow:1:1. But there is no node openflow:1:1 (there is openflow:1, maybe you meant that). Since it points nowhere it's invalid and therefore ignored.
PS: The 4.21.0 version line is pretty old and not updated anymore. See https://visjs.github.io/vis-network/examples/network/basic_usage/standalone.html for up to date Vis Network.

Add button beneath legend (or key) in Plotly.js chart

I have a Plotly.js chart. How can I position a button beneath the legend (or key)?
Here is an example of what I’m working with: https://codepen.io/synaptik/pen/YLmRMM
<div id="myDiv"></div>
<div id="inset" style="margin-left:80px;">
<button style="background:grey;">Target<br/>Info</button
</div>
A complicated but robust solution is, use javascript and get the position of the legend in the plot ( using the function getBoundingClientRect) and then set that positioning to the button, JQuery library is being used by me to do this, but can be also possible through javascript with some adjustments.
Run function after plot render:
The javascript funtion that positions the button should run only after the plotly graph has completed rendering, so based on this SO Answer, I call the function that positions the buttons after the plot has completely rendered.
References:
getBoundingClientRect
var data_x = ['2018-05-01', '2018-05-02', '2018-05-03', '2018-05-04', '2018-05-05', '2018-05-06', '2018-05-07', '2018-05-08', '2018-05-09'];
// data
var Data = {
type: 'scatter',
x: data_x,
y: [4, 2, -1, 4, -5, -7, 0, 3, 8],
mode: 'lines+markers',
name: 'Data',
showlegend: true,
hoverinfo: 'all',
line: {
color: 'blue',
width: 2
},
marker: {
color: 'blue',
size: 8,
symbol: 'circle'
}
}
// violations
var Viol = {
type: 'scatter',
x: ['2018-05-06', '2018-05-09'],
y: [-7, 8],
mode: 'markers',
name: 'Violation',
showlegend: true,
marker: {
color: 'rgb(255,65,54)',
line: {
width: 6
},
opacity: 0.5,
size: 14,
symbol: 'circle-open'
}
}
// control limits
var CL = {
type: 'scatter',
x: data_x.concat([null]).concat(data_x),
y: [5, 5, 5, 5, 6, 6, 7, 7, 7, null, -5, -5, -5, -5, -6, -6, -7, -7, -7],
mode: 'lines',
name: 'LCL/UCL',
showlegend: true,
line: {
color: 'green',
width: 2,
dash: 'dash'
}
}
// centre
var Centre = {
type: 'scatter',
x: data_x,
y: [3, 1, 2, 2, 2, -2, 2, 2, 2],
mode: 'lines',
name: 'EWMA',
showlegend: true,
line: {
color: 'grey',
width: 2
}
}
// all traces
var data = [Data, Viol, CL, Centre]
// layout
var layout = {
title: 'Basic SPC Chart',
xaxis: {
zeroline: false
},
yaxis: {
range: [data_x[0], data_x[data_x.length - 1]],
zeroline: false
}
}
function positionButton() {
var offsets = $("g.legend")[0].getBoundingClientRect();
$("div#inset").css("left", offsets.left);
var offsetTop = offsets.height + offsets.top;
$("div#inset").css("top", offsetTop);
}
Plotly.plot('myDiv', data, layout).then(function() {
window.requestAnimationFrame(function() {
window.requestAnimationFrame(function() {
positionButton();
});
});
});
$(window).on("resize", function() {
positionButton();
});
.position-button {
position: absolute;
}
.style-this {
background: grey;
}
.wrapper {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<!-- Plotly.js -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<!-- Plotly chart will be drawn inside this DIV -->
<div class="wrapper">
<div id="myDiv"></div>
<div id="inset" class="position-button">
<button class="style-this">Target<br/>Info</button
</div>
</div>
<script>
/* JAVASCRIPT CODE GOES HERE */
</script>
</body>
</html>
A simple way to do it will be, wrap the plot in a div set to relative positioning and make the div wrapping the button absolute positioned and align it to the legend. Please refer the below sample.
var data_x = ['2018-05-01' , '2018-05-02' , '2018-05-03' , '2018-05-04' , '2018-05-05' , '2018-05-06' , '2018-05-07' , '2018-05-08' , '2018-05-09' ];
// data
var Data = {
type: 'scatter',
x: data_x,
y: [4,2,-1,4,-5,-7,0,3,8],
mode: 'lines+markers',
name: 'Data',
showlegend: true,
hoverinfo: 'all',
line: {
color: 'blue',
width: 2
},
marker: {
color: 'blue',
size: 8,
symbol: 'circle'
}
}
// violations
var Viol = {
type: 'scatter',
x: ['2018-05-06', '2018-05-09'],
y: [-7,8],
mode: 'markers',
name: 'Violation',
showlegend: true,
marker: {
color: 'rgb(255,65,54)',
line: {width: 6},
opacity: 0.5,
size: 14,
symbol: 'circle-open'
}
}
// control limits
var CL = {
type: 'scatter',
x: data_x.concat([null]).concat(data_x),
y: [5,5,5,5,6,6,7,7,7, null, -5,-5,-5,-5,-6,-6,-7,-7,-7],
mode: 'lines',
name: 'LCL/UCL',
showlegend: true,
line: {
color: 'green',
width: 2,
dash: 'dash'
}
}
// centre
var Centre = {
type: 'scatter',
x: data_x,
y: [3,1,2,2,2,-2,2,2,2],
mode: 'lines',
name: 'EWMA',
showlegend: true,
line: {
color: 'grey',
width: 2
}
}
// all traces
var data = [Data,Viol,CL,Centre]
// layout
var layout = {
title: 'Basic SPC Chart',
xaxis: {
zeroline: false
},
yaxis: {
range: [data_x[0], data_x[data_x.length-1]],
zeroline: false
}
}
Plotly.plot('myDiv', data,layout);
.position-button {
position: absolute;
top: 190px;
left: 89%;
}
.style-this{
background:grey;
}
.wrapper{
position:relative;
}
<head>
<!-- Plotly.js -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<!-- Plotly chart will be drawn inside this DIV -->
<div class="wrapper">
<div id="myDiv"></div>
<div id="inset" class="position-button">
<button class="style-this">Target<br/>Info</button
</div>
</div>
<script>
/* JAVASCRIPT CODE GOES HERE */
</script>
</body>
</html>

jQuery.ajax and Rickshaw - Callback functions?

I wrote the following code. I have a json file on my server that is valid and looks like:
[
{
"data": [
{
"y": 1.0,
"x": 1451936340.0
},
{
"y": 1.0,
"x": 1451936400.0
},
{
"y": 1.0,
"x": 1451936460.0
}
]
}
]
I have the following code. I am trying to draw a line chart and overlay points on the line chart using renderer: 'multi' but I am hitting a lot of snags. I am a novice with JS and I do not understand where I am messing up. I think I need a callback function in my jQuery.ajax function but I am unsure. I appreciate any help.
<html>
<head>
<!-- css -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rickshaw/1.5.1/rickshaw.min.css">
<!-- js -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script>
jQuery.noConflict();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.10/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rickshaw/1.5.1/rickshaw.min.js"></script>
</head>
<body>
<div style="margin:10px auto;width:auto;" id="chart_container">
<div id="chart"></div>
<div id="slider"></div>
<script>
var json = jQuery.ajax({
'url': "/assets/json/data.json",
'success': function(json) {
console.log(json[0].data);
}
});
var graph = new Rickshaw.Graph( {
element: document.getElementById("chart"),
renderer: 'multi',
height: 200,
width: 400,
series: [
{
name: "series 1",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "line"
}, {
name: "series 2",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "scatterplot"
}
]
} );
graph.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview( {
graph: graph,
element: document.querySelector('#slider')
} );
var detail = new Rickshaw.Graph.HoverDetail( {
graph: graph
} );
graph.render();
</script>
</div>
</body>
There are a few things I would change here.
1.) jQuery.ajax returns a promise, not the raw data itself, so var json = jQuery.ajax(...) will not assign the json value you are expecting.
2.) pass a success callback function to properly access the JSON returned by the server
3.) Only call graph.render() once.
Javascript
jQuery.ajax({
'url': "/assets/json/data.json",
'success': renderGraph // callback for ajax success
});
// wrap graph creation logic in a function to be used as a callback
function renderGraph(json) {
var graph = new Rickshaw.Graph({
element: document.getElementById("chart"),
renderer: 'multi',
height: 200,
width: 400,
series: [{
name: "series 1",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "line"
}, {
name: "series 2",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "scatterplot"
}]
});
// remove this, only render once at the end
// graph.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.querySelector('#slider')
});
var detail = new Rickshaw.Graph.HoverDetail({
graph: graph
});
graph.render();
}

Is there any way to convert c3.js generated graph to png, and Png to Pdf in client side

I want to generate a PDF file on the client side with a graph and other tabular data coming from a JSON object.
The following is the Javascript data binding part:
BindReportToPdf: function (data) {
//data is json object
var rows = data;
var columns = [
{ title: "S.No", key: "RowNum" },
{ title: "Title", key: "TTitle" },
{ title: "Phone Number", key: "PhoneNumber" },
{ title: "Loc. Name", key: "LocationName" },
{ title: "Dept. Name", key: "DepartmentName" }
];
var doc = new jsPDF("I", "mm", "a4");
var canvas1 = document.getElementById("rptcanvas");
var content = $("#sfDepartmentbar").html();
canvg(canvas1, content, {
renderCallback: function () {
html2canvas($("#rptgraphsec"), {
onrendered: function (canvas) {
var html = '';
html += "<div style='font-size:18px;'>Report Title</div>"
html += '<div>Generated By : ' + 'sanjeev'+ '</div>';
doc.setFontSize(8);
doc.fromHTML(html, 10, 10, { 'width': 100 });
var imgData = canvas.toDataURL('image/png');
doc.addImage(imgData, 'PNG', 5, 55, 200, 100);
if (data.length > 0) {
doc.autoTable(columns, rows, {
startX: 5,
startY: 165,
margin: 5,
tableWidth: 'auto',
theme: 'grid',
lineWidth: 0.1,
fillStyle: 'F',
pageBreak: 'auto',
styles: {
overflow: 'linebreak',
fontSize: 10,
},
headerStyles: {
fillColor: [53, 133, 201],
columnWidth: 'auto',
rowHeight: 10,
cellPadding: 0.5,
halign: 'center',
valign: 'middle',
},
bodyStyles: {
columnWidth: 'wrap',
rowHeight: 8,
halign: 'left',
valign: 'middle',
cellPadding: 0,
halign: 'center',
valign: 'middle',
},
});
}
doc.save("Report.pdf");
}
});
}
});
}
And the html Part is:
<div id="rptgraphsec">
<div class="graphWrapper">
<div id="sfDepartmentbar">
// At here c3.js generated svg + div graph remains
</div>
<canvas id="rptcanvas" width="800px" height="300px"></canvas>
</div>
</div>
The PDF file is generated with all tabular data and format, except the SVG graph section. All the JavaScript code used is within tag sections. Any ideas about what can be wrong?
You can use a svg to canvas library such as Fabric.js to render the SVG. html2canvas has already support for svg rendering if you provide the svg extension available here.

Double donut-like chart with negative values

I've been asked to do this kind of graph (40,9% and 16,4% are examples, they should indicate something like -6% and 9%):
Any idea on how I can get that kind of result, using a javascript library, if possible (but it is not a must) Highcharts?
Thanks
It's possible with HighCharts, Documentation
e.g.
$(function () {
data = [{
valSecond: 25,
valFirst: 62.5
}];
// Build the data arrays
var secondData = [];
var firstData = [];
for (var i = 0; i < data.length; i++) {
// add second data
secondData.push({
name: "Second",
y: data[i].valSecond,
color: "#00FF00"
});
// add first data
firstData.push({
name: "First",
y: data[i].valFirst,
color:'#FF0000'
});
}
// Create the chart
$('#container').highcharts({
chart: {
type: 'pie'
},
title: {
text: ''
},
plotOptions: {
pie: {
animation: false,
shadow: false,
center: ['50%', '50%']
}
},
tooltip: {
valueSuffix: '%'
},
series: [{
name: 'second',
data: secondData,
size: '30%',
startAngle: 270,
endAngle: 360,
innerSize: '20%'
}, {
name: 'first',
color:'#FFFFFF',
data: firstData,
size: '80%',
startAngle: 0,
endAngle: 225,
innerSize: '60%',
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="width: 600px; height: 400px; margin: 0 auto"></div>
Jsfiddle
In the highcharts you can adapt donut chart http://www.highcharts.com/demo/pie-donut, remove connectors, set useHTML for dataLabels and rotate by css / rotation SVG element. Missing elements can by added by renderer.

Categories