I am not very conversant with javascript.I have a jquery datatable loaded using an ajax call as follows:
$('#table').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "http://api.mywebsite.com/report",
"columns": [
{ "data": "date" },
{ "data": "ordernumber" },
{ "data": "totalsales" },
{ "data": "subtotal" }
]
} );
I want to load the dataTable together with a Google chart but I have no clue how to get the data object from above dataTable initialization to the the Google code below and trigger the same routine every time the datable is re-populated:
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Sales'],
['20 Jan - Feb 04', 10340 ],
['20 Feb - Mar 05', 23470 ],
['20 June - Dec 06', 450 ],
['20 Mar - Aug 07', 3030 ]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Is there a way I can replace below
`['Date', 'Sales'],
['20 Jan - Feb 04', 10340 ],
['20 Feb - Mar 05', 23470 ],
['20 June - Dec 06', 450 ],
['20 Mar - Aug 07', 3030 ]`
with something like:
dataTable.data[date]
This is quite easy. I notice you are using dataTables 1.10.x, and then you can use the API to iterate over each row, and build up a data array google visualization will use :
$("#buildChart").click(function() {
var dataArray = [];
dataArray.push([ 'date', 'totalsales' ]);
table.rows().data().each(function(value, index) {
dataArray.push([ value.date, value.totalsales ]);
});
drawChart(dataArray);
});
and the called drawChart function is pretty much like the one in your question :
function drawChart(dataArray) {
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'dataTables to google visualization'
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
see demo using your data -> http://jsfiddle.net/9wvvh8sk/
Related
I am trying to create a line, spline chart using JSON data. I want multiple series but I am confused on how to do that. Right now I am able to create the multiple series when the date is in 2019-07-06 format. I also have a JSON that has a column for the month and a column for the year Please help on how I can fix this. Right now I only have the code for group by day.
JSON Data:
[
{ "month": 6,
"year": 2019,
"starts": 21278998,
"completes": 9309458
},
{ "month": 7,
"year": 2019,
"starts": 38850115,
"completes": 17790105
}
]
I used the solution for the date format 2019-07-06 provided in this fiddle: https://jsfiddle.net/BlackLabel/tjLvh89b/
Please help with how I can create a chart for the Month, Year on the x-Axis.
You can achieve it simply by creating a Date object using different parameters.
Instead of the string date parameter new Date('2019-07-07') use year and month as separate parameters like that: new Date(2019, 7).
Code:
var json = [{
month: 6,
year: 2019,
starts: 21278998,
completes: 9309458
}, {
month: 7,
year: 2019,
starts: 38850115,
completes: 17790105
}];
var series1 = {
name: 'starts',
data: []
},
series2 = {
name: 'completes',
data: []
};
json.forEach(elem => {
series1.data.push({
x: +new Date(elem.year, elem.month),
y: elem.starts
});
series2.data.push({
x: +new Date(elem.year, elem.month),
y: elem.completes
});
});
Highcharts.chart('container', {
chart: {
type: 'spline'
},
xAxis: {
type: 'datetime'
},
series: [
series1,
series2
]
});
Demo:
https://jsfiddle.net/BlackLabel/xtefuLsp/1/
Date object reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
How Can I append text to c3.js regions? I have three regions in my chart and I would like to append three different texts to them. So far I have tried to use d3.js but with no success
var rectOffset = (( d3.select(this).attr("x") ) * 1) + 25;
d3.selectAll(".c3-region-0 rect")
.append("text")
.text("Some Text")
.attr("dy","15px")
.attr("dx",rectOffset+"px")
I get an error
TypeError: Cannot read property 'getAttribute' of null
at Array.d3_selectionPrototype.attr (d3.js:578)
jsfiddle
code:
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
["x", "2016-01-04", "2016-01-05", "2016-01-06", "2016-01-07", "2016-01-08", "2016-01-09", "2016-01-10", "2016-01-11", "2016-01-12", "2016-01-13", "2016-01-14", "2016-01-15", "2016-01-16", "2016-01-17", "2016-01-18", "2016-01-19", "2016-01-20", "2016-01-21", "2016-01-22", "2016-01-23", "2016-01-24", "2016-01-25", "2016-01-26", "2016-01-27", "2016-01-28", "2016-01-29", "2016-01-30", "2016-01-31", "2016-02-01", "2016-02-02", "2016-02-03"],
["Democrates", 49.85, 49.89, 49.82, 49.51, 49.42, 49.33, 49.24, 49.64, 49.57, 49.57, 49.01, 48.67, 48.7, 48.7, 48.7, 48.63, 48.63, 48.63, 48.63, 48.63, 48.61, 48.61, 48.68, 48.76, 48.84, 48.73, 48.76, 48.79, 48.81, 49.68, 49.63],
["Republicans", "50.15", "50.11", "50.18", "50.49", "50.58", "50.67", "50.76", "50.36", "50.43", "50.43", "50.99", "51.33", "51.30", "51.30", "51.30", "51.37", "51.37", "51.37", "51.37", "51.37", "51.39", "51.39", "51.32", "51.24", "51.16", "51.27", "51.24", "51.21", "51.19", "50.32", "50.37"]
],
colors: {
Democrates: '#4575b4',
Republicans: '#d73027'
},
},
axis: {
x: {
type: 'timeseries',
max: '2016-11-08',
tick: {
values: ["2016-02-01", "2016-06-14", "2016-11-08", "2016-09-26", "2016-10-19", "2016-07-18", "2016-07-28" ],
format: function (x) {
if (x == "Mon Feb 01 2016 00:00:00 GMT+0100 (CET)"){
return 'Feb 01' + 'Primaries and Caucuses '
} else if (x == "Tue Nov 08 2016 00:00:00 GMT+0100 (CET)") {
return 'Nov 08 Election Day'
} else if (x == "Mon Sep 26 2016 00:00:00 GMT+0200 (CEST)") {
return ' Sep 26 Start of Presidential Debates'
} else if (x == "Mon Jul 18 2016 00:00:00 GMT+0200 (CEST)") {
return 'Jul 25 Announcement of Nominees'
} else {
var format= d3.time.format("%b %d");
var date = format(x)
return date
}},
fit: false
}
}
},
grid: {
y: {
lines: [
{value: 50},
]
},
x: {
lines: [
{value: "2016-01-08", text: "Want to rorate this text in 180 degrees",
class: "xLineLable", position: "end"}
]
}
},
regions: [
{axis: 'x', start: "2016-02-01", end: "2016-06-14", class: 'regionX'},
{axis: 'x', start: "2016-07-18", end: "2016-07-28", class: 'regionX'},
{axis: 'x', start: "2016-09-26", end: "2016-10-19", class: 'regionX'}
]
});
You can't add text to a rect, you'll need to add it as a sibling element under the c3-region group element, which is a bit of a pain in d3 (and rectoffset needs to be a function, or the d3.select(this) gets the top-level dom node). In rectOffset I select the text's parentNode, then grab it's rect child node.
There were a couple of other gotchas that stopped the text turning up that I didn't expect.. attr always returns a string so .attr(x)+25 would return "75"+25 -> 7525, needed to cast to a number with '+'... I ended up using text-anchor instead anyways. Plus the fill-opacity needed to be adjusted for the text to be seen even when in the right spot. That had me flummoxed for a while.
var rectOffset = function () { return +d3.select(this.parentNode).select("rect").attr("x"); };
d3.selectAll(".c3-region-0")
.append("text")
.text("Some Text")
.attr("dy","15")
.attr("dx",rectOffset)
.style("fill-opacity", 1)
.attr("text-anchor", "start")
;
http://jsfiddle.net/yrzxj3x2/35/
I have a table with data columns defined like this:
var table = myEl.DataTable({
paging: false,
searching: true,
info: false,
ordering: true,
autoWidth: false,
columns: [
{data: 'Name', name: 'Name'},
{data: 'Time', name: 'Time'}
]
});
The data that feed this table look like this:
{
Name: "Bob",
Time: "Wed Aug 26 2015 16:09:52 GMT-0500 (Central Daylight Time)",
TimeTwo: "16:09:52"
}
So DataTables stores the entire object and displays Name and Time.
How can I switch the data source as defined in "columns" in initialization to using TimeTwo rather than Time? (after the table gets data fed into it)
Simply: The table loads Name and Time, but how can I switch it to using TimeTwo after initialization? Switch it dynamically?
function switchDataSourceForTime(){
// what to do...?
}
You can make both columns are rendered but only one is shown. Something like this:
<div>
Toggle column:
<input id="btn" type="button" value="change column value"></input>
</div>
<br>
<div>
<table id="table"></table>
</div>
var data =
[
{
Name: "Bob",
Time: "Wed Aug 26 2015 16:09:52 GMT-0500 (Central Daylight Time)",
TimeTwo: "16:09:52"
},
{
Name: "Tom",
Time: "Wed Aug 25 2015 17:41:23 GMT-0500 (Central Daylight Time)",
TimeTwo: "17:41:23"
}
];
var table = $("#table").DataTable({
data: data,
paging: false,
searching: true,
info: false,
ordering: true,
autoWidth: false,
columns: [
{data: 'Name', name: 'Name'},
{data: 'Time', name: 'Time'},
{data: 'TimeTwo', name: 'TimeTwo'}
]
});
table.column("2").visible(false);
$('#btn').on('click', function(e){
e.preventDefault();
var columnTimeTwo = table.column("2").visible(!table.column("2").visible());
var columnTime = table.column("1").visible(!table.column("1").visible());
});
You can see the code running on fiddle
columnValue = columnValue.get('Name');
give me Name of the release
but not able to read ReleaseDate
columnvalue1 = columnValue.get('ReleaseEndDate');
this gives me error
Uncaught TypeError: undefined is not a function
This is my release object
columnValue value
j {phantom: false, internalId: "ext-record-2", raw: Object, data: Object, modified: Object…}
data: Object
CreationDate: null
GrossEstimateConversionRatio: ""
Name: "Release 24"
Notes: ""
ObjectID: 12788620953
PlannedVelocity: null
Project: ""
ReleaseDate: Wed Sep 17 2014 10:29:59 GMT+0530 (India Standard Time)
ReleaseStartDate: Wed Jul 23 2014 10:30:00 GMT+0530 (India Standard Time)
RevisionHistory: ""
Release object has ReleaseStartDate and ReleaseDate. There is no ReleaseEndDate in WS API.
Use ReleaseDate.
Try this example of a simple grid from the guide. Replace model: 'userstory' with model: 'release', and use config:
columnCfgs:[
'Name',
'ReleaseStartDate',
'ReleaseDate'
]
You should see ReleaseDate.
Then try custom data example from the grid that requires explicit fetching of ReleaseDate. Modify that example to display a grid of releases instead of a grid of user stories. You may do something like this to create a custom column Release Dates based on values of both ReleaseStartDate and ReleaseDate:
launch: function() {
Ext.create('Rally.data.wsapi.Store', {
model: 'release',
autoLoad: true,
listeners: {
load: this._onDataLoaded,
scope: this
},
fetch: ['Name', 'ReleaseStartDate', 'ReleaseDate']
//fetch: ['Name', 'ReleaseStartDate']
});
},
_onDataLoaded: function(store, data) {
var records = _.map(data, function(record) {
console.log(record);
return Ext.apply({
ReleaseDates: record.get('ReleaseStartDate') + " -- " + record.get('ReleaseDate')
}, record.getData());
});
this.add({
xtype: 'rallygrid',
showPagingToolbar: false,
showRowActionsColumn: false,
editable: false,
store: Ext.create('Rally.data.custom.Store', {
data: records
}),
columnCfgs: [
{
text: 'Name',
dataIndex: 'Name'
},
{
text: 'Release Dates',
dataIndex: 'ReleaseDates',
flex: 1
}
]
});
}
This should also display ReleaseDate as long as fetch includes ReleaseDate fetch: ['Name', 'ReleaseStartDate',ReleaseDate']
The problem is likely to be related to your code. Start with working examples as above and see if ReleaseDate is returned.
I have the following
<div id="chart"></div>
<script src="js/flot/jquery.flot.js"></script>
<script src="js/flot/jquery.flot.tooltip.min.js"></script>
<script src="js/flot/jquery.flot.resize.js"></script>
var sessions = [
[1418706000000, 14813],
[1418792400000, 39580],
[1418878800000, 51193],
[1418965200000, 66700],
[1419051600000, 108737],
[1419138000000, 101081],
[1419224400000, 94449],
[1419310800000, 109039],
[1419397200000, 92329],
[1419483600000, 68942],
[1419570000000, 75391],
[1419656400000, 120016],
[1419742800000, 132495],
[1419829200000, 103469],
[1419915600000, 88940],
[1420002000000, 59938],
[1420088400000, 72359],
[1420174800000, 74663]
];
var users = [
[1418706000000, 2632],
[1418792400000, 9588],
[1418878800000, 9273],
[1418965200000, 10839],
[1419051600000, 14948],
[1419138000000, 11226],
[1419224400000, 13394],
[1419310800000, 10493],
[1419397200000, 8482],
[1419483600000, 2375],
[1419570000000, 5783],
[1419656400000, 10068],
[1419742800000, 8288],
[1419829200000, 5423],
[1419915600000, 4866],
[1420002000000, 1862],
[1420088400000, 5560],
[1420174800000, 1257]
];
function doPlot(position) {
$.plot($("#chart"), [{
data: sessions,
label: "Sessions"
}, {
data: revenue,
label: "Revenue",
yaxis: 2
}], {
xaxes: [{
mode: 'time'
}],
yaxes: [{
min: 0
}, {
alignTicksWithAxis: position == "right" ? 1 : null,
position: position
}],
legend: {
position: 'sw'
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%s for %x was %y",
xDateFormat: "%y-%0m-%0d",
onHover: function (flotItem, $tooltipEl) {
}
}
});
}
doPlot("right");
Thhis displays figures for both sessions and users on dates that there isn't even data for. The last date that there is data for is Dec 27th. Yet, this line graph shows data for up until Jan 2nd.
Here is a working example here
Any ideas?
According to your last data entry in each array element time = 1420174800000, so:
var date = new Date(1420174800000);
// output "Fri, 02 Jan 2015 05:00:00 GMT"
console.log(date.toGMTString());
I converted your data to dates:
date = new Date(sessions[i][0])
It contains dates between Dec 16 2014 and Jan 02 2015. You can see it in this fiddle.
When you fill your arrays, you should convert your dates to numbers simply with:
sessions[i] = [Number(date), value];
I'm not sure how you meant Date('D, M j'), I assume it's a string like "Date(month,day,year)". An example of converting this kinf of json to plottable data: in this other fiddle.
Actually, I reversed the day and month, but you get the idea. :)