I'm trying to display x- and y-axis to my charts.
I'm using JSON for the data.
This is my following code :
new Rickshaw.Graph.Ajax( {
element: document.getElementById("chart"),
width: 580,
height: 300,
renderer: 'line',
dataURL: 'dataoutevo.json',
onData: function(d) {
return d },
onComplete: function(transport) {
var graph = transport.graph;
var hoverDetail = new Rickshaw.Graph.HoverDetail( {
graph: graph
} );
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle( {
graph: graph,
legend: legend
} );
},
series: [
{
name: 'ligne1',
color: '#c05020',
}, {
name: 'ligne2',
color: '#30c020',
}, {
name: 'ligne3',
color: '#6060c0'
}, {
name: 'ligne4',
color: 'red'
}
],
onComplete: function() {
var x_axis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
x_axis.graph.update();
}
}
);
Can anyone help me and tell me how to do it ?
I have numbers as x- and y-datas (not words)
new Rickshaw.Graph.Ajax( {
element: document.getElementById("chart"),
width: 580,
height: 300,
renderer: 'line',
dataURL: 'dataoutevo.json',
onData: function(d) { d[0].data[0].y = 80; return d },
onComplete: function(transport) {
// important . do not forget
var graph = transport.graph;
var detail = new Rickshaw.Graph.HoverDetail({ graph: graph });
var legend = new Rickshaw.Graph.Legend({graph: graph,element: document.querySelector('#legend')});
var xAxis = new Rickshaw.Graph.Axis.Time({graph: graph});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y({graph: graph});
yAxis.render();
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
},
series: [
{
name: 'ligne1',
color: '#c05020',
}, {
name: 'ligne2',
color: '#30c020',
}, {
name: 'ligne3',
color: '#6060c0'
}, {
name: 'ligne4',
color: 'red'
}
],
});
Changing Rickshaw.Graph.Axis.Time to Rickshaw.Graph.Axis.X worked for me in a very similar situation. BTW your example code shows two definitions of onComplete, which I assume isn't intended?
Related
I would like to lead with google charts is brand new to me and I could be making a really dumb mistake. I have been working on this all day and no matter what I do, I can't get my google chart to draw using my json data. I think it has something to do with the columns and rows. I've made alot of changes different ways and I've given up at the below information. I'm not getting any errors but my chart isn't loading. I've looked at so many threads and examples now that nothing is making sense. Any help is appreciated!
<div class="col-lg-12">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="pieDisconnectReasonsChart" style="min-height:271px"></div>
</div>
<script>
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawDisconnectReasonsChart);
function drawDisconnectReasonsChart() {
var jsonData = $.ajax({
url: "/Reports/RunDisconnectReasonsReport",
type: "POST",
dataType: "json",
data: {
openDate: #Html.Raw(Json.Encode(Model.OpenDate)),
closeDate: #Html.Raw(Json.Encode(Model.CloseDate)),
},
})
.done(function (jsonData) {
var data = new google.visualization.DataTable(jsonData);
data.addColumn("string", "SY_OPEN_LBL");
data.addColumn("string", "SY_DESCRIPTION");
data.addColumn("number", "TOTAL");
data.addColumn("number", "PERCTWODEC");
data.addColumn("number", "PERC");
data.addColumn("number", "ErrMsg");
Object.keys(jsonData).forEach(function (row) {
data.addRow([
row.SY_DESCRIPTION,
row.SY_OPEN_LBL,
row.TOTAL,
row.PERCTWODEC,
row.PERC,
row.ErrMsg
]);
});
var options = {
title: 'Disconnect Reasons',
titleTextStyle: { color: 'black', fontSize: 22, bold: true },
legend: {
position: 'bottom', textStyle: { fontSize: 8 }, alignment: 'center'
},
chartArea: {
width: '98%', height: '80%'
}
};
var chart = new google.visualization.PieChart(document.getElementById('pieDisconnectReasonsChart'));
debugger;
chart.draw(data, options);
});
};
</script>
the data format for a pie chart only allows for two data table columns.
one string and one number.
unless you're providing a custom tooltip, then a third string column is allowed.
next, you're manually adding columns and rows to the data table,
so you need to remove the jsonData variable from the constructor, here...
from...
var data = new google.visualization.DataTable(jsonData); // <-- remove jsonData
to...
var data = new google.visualization.DataTable();
if you want to create the data table directly from json,
the json must be in a specific format, found here...
Format of the Constructor's JavaScript Literal data Parameter
with the above method, you would not need to manually add columns and rows,
and the chart would be faster, depending on the amount of data anyway...
try removing the extra columns and correcting the constructor,
and it should work, similar to the following working snippet...
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawDisconnectReasonsChart);
function drawDisconnectReasonsChart() {
var data = new google.visualization.DataTable();
data.addColumn("string", "SY_OPEN_LBL");
data.addColumn("number", "TOTAL");
data.addRow([
'CAT A',
2
]);
data.addRow([
'CAT B',
6
]);
var options = {
title: 'Disconnect Reasons',
titleTextStyle: { color: 'black', fontSize: 22, bold: true },
legend: {
position: 'bottom', textStyle: { fontSize: 8 }, alignment: 'center'
},
chartArea: {
width: '98%', height: '80%'
}
};
var chart = new google.visualization.PieChart(document.getElementById('pieDisconnectReasonsChart'));
chart.draw(data, options);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="pieDisconnectReasonsChart" style="min-height:271px"></div>
EDIT
in the done method,
it appears your looping on the keys of your json object.
Object.keys(jsonData).forEach(function (row) {
instead, loop on the json object itself.
jsonData.forEach(function (row) {
see following snippet...
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawDisconnectReasonsChart);
function drawDisconnectReasonsChart() {
var jsonData = $.ajax({
url: "/Reports/RunDisconnectReasonsReport",
type: "POST",
dataType: "json",
data: {
openDate: #Html.Raw(Json.Encode(Model.OpenDate)),
closeDate: #Html.Raw(Json.Encode(Model.CloseDate)),
},
}).done(function (jsonData) {
var data = new google.visualization.DataTable();
data.addColumn("string", "SY_OPEN_LBL");
data.addColumn("number", "TOTAL");
jsonData.forEach(function (row) {
data.addRow([
row.SY_DESCRIPTION,
row.TOTAL
]);
});
var options = {
title: 'Disconnect Reasons',
titleTextStyle: { color: 'black', fontSize: 22, bold: true },
legend: {
position: 'bottom', textStyle: { fontSize: 8 }, alignment: 'center'
},
chartArea: {
width: '98%', height: '80%'
}
};
var chart = new google.visualization.PieChart(document.getElementById('pieDisconnectReasonsChart'));
chart.draw(data, options);
});
};
I am currently using Cytoscape JS to visualize a network but I would like to overlay the graph on a world map and plot the nodes to specific locations. The Tokyo Railways Demo is similar to what I have imagined but the background is black. I want my map to look like the google maps and have similar zoom in and out capabilities. It would be great if there is a way to integrate the google maps in the Cytoscape graph.
Cytoscape.js on Google Maps, a demo code based on a sample overlay-simple. The current state is rough, but it works.
Try running the code below in full screen. To zoom IN/OUT, use press_Ctrl + scroll_wheel.
The best platform to test this code is jsfiddle.net, by forking the original code and replacing parts with the code presented here.
/*
Status: google_APIkey is good for development only
*/
// This example creates a custom overlay called CyOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.
// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class therefore
// it's simpler to load the API synchronously, using
// google.maps.event.addDomListener().
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.
// some data here
var cyto_divid = 'cy'; //outside, below gmaps
var goverlay_id = 'cy4'; //overlay on gmaps
var timeoutsec = 500; //millisec
var cy;
var base_dc = 0.03; //TODO: derive a formula
var lon_ext = 25; //extent in lng
var lonmin = 90.0; //90
var latmin = 0; //0
var lon_cor = lon_ext*base_dc;
var lat_ext = lon_ext; //extent in lat
var lonmax = lonmin + lon_ext;
var lonmid = (lonmin+lonmax)/2;
var lonmax2 = lonmax + lon_cor;
var latmax = latmin + lat_ext;
var latmid = (latmin+latmax)/2;
var latlng = { lat: latmin, lng: lonmin};
var latlng2 = { lat: latmax, lng: lonmax2};
var clatlng = { lat: latmid, lng: lonmid};
var cbottom = { lat: latmin, lng: lonmid};
function lnglat2xy(lon, lat) {
let w = 500;
let h = 500;
let L = lonmax2-lonmin;
let B = latmax-latmin;
let y = (B-(lat-latmin))*h/B;
let x = (lon-lonmin)*w/L;
return {x: x, y: y};
}
var bkk = lnglat2xy(100.494, 13.75);
var bda = lnglat2xy(95.502586, 5.412598);
var hoc = lnglat2xy(106.729, 10.747);
var han = lnglat2xy(105.90673, 21.03176);
var chi = lnglat2xy(99.837, 19.899);
var nay = lnglat2xy(96.116, 19.748);
var overlay;
CyOverlay.prototype = new google.maps.OverlayView();
// Initialize the map and the custom overlay.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5, //11,
center: {
lat: (latmax+latmin)/2, //62.323907,
lng: (lonmax2+lonmin)/2 //-150.109291
},
mapTypeId: 'roadmap' //
});
map.addListener('zoom_changed', function() {
setTimeout(function delay() {
cy.fit(cy.$('#LL, #UR'));
}, timeoutsec)
});
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(latmin, lonmin), //62.281819, -150.287132)
new google.maps.LatLng(latmax, lonmax2)); //62.400471, -150.005608))
// The photograph is courtesy of the U.S. Geological Survey.
var srcImage;
/*srcImage = 'https://developers.google.com/maps/documentation/' +
'javascript/examples/full/images/talkeetna.png';*/
// The custom CyOverlay object contains the USGS image,
// the bounds of the image, and a reference to the map.
overlay = new CyOverlay(bounds, srcImage, map);
// init cytoscape
setTimeout(function delay() {
cyto_run();
}, timeoutsec)
}
/** #constructor */
function CyOverlay(bounds, image, map) {
// Initialize all properties.
this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;
// Define a property to hold the image's div. We'll
// actually create this div upon receipt of the onAdd()
// method so we'll leave it null for now.
this.div_ = null;
// Explicitly call setMap on this overlay.
this.setMap(map);
}
/**
* onAdd is called when the map's panes are ready and the overlay has been
* added to the map.
*/
CyOverlay.prototype.onAdd = function() {
var div = document.createElement('div');
div.id = goverlay_id;
div.style.borderStyle = 'dashed';
//div.style.backgroundColor = rgba(76,76,76,0.25);
div.style.opacity = 0.8;
div.style.borderWidth = '1px';
div.style.borderColor = 'gray';
div.style.position = 'absolute';
// Create the img element and attach it to the div.
var img = document.createElement('img');
img.src = this.image_;
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'absolute';
//div.appendChild(img); //ignore overlay img
this.div_ = div;
// Add the element to the "overlayLayer" pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
CyOverlay.prototype.draw = function() {
// We use the south-west and north-east
// coordinates of the overlay to peg it to the correct position and size.
// To do this, we need to retrieve the projection from the overlay.
var overlayProjection = this.getProjection();
// Retrieve the south-west and north-east coordinates of this overlay
// in LatLngs and convert them to pixel coordinates.
// We'll use these coordinates to resize the div.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's div to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
/*
cytoscape needs regen here
*/
setTimeout(function delay() {
cy.fit(cy.$('#LL, #UR'));
}, timeoutsec)
};
// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
CyOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
google.maps.event.addDomListener(window, 'load', initMap);
/* ___________cytoscape.js code____________ */
function cyto_run() {
cy = cytoscape({
container: document.getElementById(goverlay_id),
elements: {
nodes: [
{data: {id: "LL", nname: "LowerLeft"},
classes: "controlpoint",
position: {x: 0, y: 500}},
{data: {id: "UL", nname: "UpperLeft"},
classes: "controlpoint",
position: {x: 0, y: 0}},
{data: {id: "UR", nname: "UpperRight"},
classes: "controlpoint",
position: {x: 500, y: 0}},
{data: {id: "LR", nname: "LowerRight"},
classes: "controlpoint",
position: {x: 500, y: 500}},
{data: {id: "bkk", name: "Bangkok"}, classes: "datapoint", position: {x: bkk.x, y: bkk.y}},
{data: {id: "bda", name: "Banda"}, classes: "datapoint", position: {x: bda.x, y: bda.y}},
{data: {id: "hoc", name: "Hochi"}, classes: "datapoint", position: {x: hoc.x, y: hoc.y}},
{data: {id: "han", name: "Hanoi"}, classes: "datapoint", position: {x: han.x, y: han.y}},
{data: {id: "nay", name: "Nay"}, classes: "datapoint", position: {x: nay.x, y: nay.y}},
],
edges: [
{data: {source: "nay", target: "bda", label: "NAB"},
classes: 'autorotate'},
{data: {source: "nay", target: "han", label: "NAH"},
classes: 'autorotate'},
{data: {source: "bda", target: "bkk", label: "dgfh"}},
{data: {source: "hoc", target: "bkk", label: "tert"}},
{data: {source: "hoc", target: "bda", label: "HOB"},
classes: 'autorotate'},
{data: {source: "hoc", target: "han", label: "HOH"},
classes: 'autorotate'},
{data: {source: "han", target: "bkk", label: "terf"}},
{data: {id: "LLUR" , source: "LL", target: "UR"},
classes: "controlline"},
{data: {id: "ULLR" , source: "UL", target: "LR"},
classes: "controlline"},
]
},
style: [
{
selector: "node.datapoint",
style: {
shape: "ellipse",
width: '12px',
height: '12px',
"background-color": "blue",
label: "data(name)",
opacity: 0.85,
"text-background-color": "yellow"
}
},
{
selector: "node.controlpoint",
style: {
shape: "triangle",
width: '4px',
height: '4px',
"background-color": "blue",
label: "data(id)",
opacity: 0.85,
}
},
{
selector: "edge[label]",
style: {
label: "data(label)",
width: 2,
"line-color": "#909",
"target-arrow-color": "#f00",
"curve-style": "bezier",
"target-arrow-shape": "vee",
//"target-arrow-fill": "red",
"arrow-scale": 1.0,
}
},
{
"selector": ".autorotate",
"style": {
"edge-text-rotation": "autorotate"
}
},
{
"selector": ".controlline",
"style": {
width: "2px",
"line-color": "green",
opacity: 0.35
}
},
{
selector: ".highlight",
css: {
"background-color": "yellow"
}
}
],
layout: {
name: "preset"
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#cy {
width: 600px;
height: 600px;
position: absolute;
}
#cy4 {
width: 600px;
height: 600px;
position: absolute;
}
<b>Cytoscape on Google Maps</b>
<div id="map"></div>
<div id="cy"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.9.2/cytoscape.min.js"></script>
There is a plugin cytoscape-mapbox-gl, which intergrates Cytoscape.js and Mapbox GL JS. It can be used with any raster or vector basemap layer.
I'm the author.
I use the piwik php api to generate data like this:
[
{"label":"1680x1050","nb_visits":9,"nb_actions":53,"max_actions":27,"sum_visit_length":3051,"bounce_count":3,"nb_visits_converted":0,"sum_daily_nb_uniq_visitors":7,"sum_daily_nb_users":0,"segment":"resolution==1680x1050"},
{"label":"1440x900","nb_visits":1,"nb_actions":1,"max_actions":1,"sum_visit_length":0,"bounce_count":1,"nb_visits_converted":0,"sum_daily_nb_uniq_visitors":1,"sum_daily_nb_users":0,"segment":"resolution==1440x900"}
]
and i want to use chart.js to visualize this data, at the moment my code looks like this and doesn't work:
var chartjsData = [];
var chartjsLabel = [];
$.getJSON("piwik.php", function (json) {
///src = http://stackoverflow.com/questions/24696329/how-to-use-json-data-in-chart-js
for (var i = 0; i < json.length; i++) {
chartjsData.push(json[i].nb_visits);
chartjsLabel.push(json[i].label);
}
});
var barChartData = {
labels :[chartjsLabel],datasets : [
{
fillColor : "rgba(220,280,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : chartjsData
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: barChartData,
});
can maybe someone give me a working example how to work with chart.js and piwik's json data, or a hint how to get this working, thanks alot!
I got it like this:
var label = [];
var data = [];
$.getJSON("piwik.php", function (json) {
for (var i = 0; i < json.length; i++) {
label.push(json[i].label);
data.push(json[i].nb_visits);
}
graph();
});
function graph(){
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: '',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
options: {
}
});
};
I have a simple column chart. using the google-charts API:
JS code:
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $str ?>);
var options = {
title: 'Business Optimization Per Predicted Conversion Rate',
bar: {groupWidth: "70%"},
colors: ['purple','grey'],
fontSize:20,
legend: { position: "none" },
width: 900,
backgroundColor: { fill: '#efeff0'},
};
var chart = new google.charts.Bar(document.getElementById('chart_div_1'));
chart.draw(data, google.charts.Bar.convertOptions(options));
My question is: How can i draw simple line here?
Horizontly to the X-axis.
As I was looking at the question How do I select which columns from my CSV to chart with HighChart? I tried to apply it using a csv file but I could not get it to work!
What am I doing wrong? Thank you in advance:
$(function () {
//var data = "Year,Month,Day,Hour,Time,kWh,Savings,Total kWh\n2013,02,06,11,11:00,0,0,308135\n2013,02,06,11,11:59,15,1.875,308150\n2013,02,06,12,12:59,27,3.375,308177\n2013,02,06,13,13:59,34,4.25,308211\n2013,02,06,14,14:59,32,4,308243";
var options = {
chart: {
renderTo: 'EXAMPLE',
defaultSeriesType: 'line'
},
title: {
text: 'Current Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: hassayampa.csv',
x: -20
},
xAxis: {
type: 'datetime'
},
yAxis:{
title: {
text: 'Temperature (\xB0C)'
},
//min: 0
},
legend:{
layout: 'vertical',
//backgroundColor: '#FFFFFF',
//floating: true,
align: 'left',
//x: 100,
verticalAlign: 'top',
//y: 70,
borderWidth: 0
},
series: [{
name: 'PRIM OUT TEMP',
data: []
}, {
name: 'SEC OUT TEMP',
data: []
}]
};
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
});
new Highcharts.Chart(options);
});
Here is the jsfiddle:http://jsfiddle.net/tonystinge/3bQne/1223/
I got it now...
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
// parsing here...
});
new Highcharts.Chart(options);
});
Your problem is the placement of the new Highcharts.Chart(options) call. $.get (like most ajax calls) is asynchronous So the new Highcharts will be called before it completes.
Change it to this:
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
new Highcharts.Chart(options); // this is now in the $.get callback function
});