Can not read property "__" of undefined - meteor

I am currently working for my school project and using Meteor with AngularJs 1 and ES6. In one of my views I try to update some live data (with AngularCharts) every second which are currently randomly generated. I am new to the way of how Meteor and ES6 works, so I think a have a pretty easy error.
This is my code of the class from the view:
class View2 {
constructor($interval, $scope) {
'ngInject';
this.cardRow = [
{name: 'Drilling Heat', color: 'white', value: 0},
{name: 'Drilling Speed', color: 'white', value: 0},
{name: 'Milling Heat', color: 'white', value: 0},
{name: 'Milling Speed', color: 'white', value: 0}
];
this.type = ['bar', 'line', 'pie', 'doughnut', 'radar'];
this.chartRow = [
{
name: 'Chart1',
type: 'bar',
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
series: ['Series A'],
data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
datasetOverride: [{yAxisID: 'y-axis-1'}],
options: {
animation: false,
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
}]
}
}
},
{
name: 'Chart2',
type: 'line',
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
series: ['Series A'],
data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
datasetOverride: [{yAxisID: 'y-axis-1'}],
options: {
animation: false,
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
}]
}
}
}
];
$interval(this.update, 1000);
}
update() {
for (var i = 0; i < this.cardRow.length; i++) {
this.cardRow[i].value = Math.round((Math.random() * 10) * 10);
var value = this.cardRow[i].value;
switch (true) {
case (value > 80):
this.cardRow[i].color = 'red';
break;
case (value > 60):
this.cardRow[i].color = 'orange';
break;
case (value > 40):
this.cardRow[i].color = 'yellow';
break;
default:
this.cardRow[i].color = 'green';
break;
}
}
for (var y = 0; y < this.chartRow.length; y++) {
for (var z = 0; z < this.chartRow[y].data.length; z++) {
this.chartRow[y].data[z] = this.chartRow[y].data[z + 1];
}
this.chartRow[y].data[z - 1] = Math.round((Math.random() * 10) * 10);
}
}
}
The $interval should call the function "update" every second but then the variable is unknown. it throws an error like this:
TypeError: Cannot read property 'length' of undefined
at update (view2.js:74)
at callback (modules.js?hash=7db65c4…:46346)
at Scope.$eval (modules.js?hash=7db65c4…:51381)
at Scope.$digest (modules.js?hash=7db65c4…:51194)
at Scope.$apply (modules.js?hash=7db65c4…:51489)
at tick (modules.js?hash=7db65c4…:46336)
What can I do to solve this problem? And is there a way to use Meteor with the old Javascript Version?

Related

unable to access reactive nested object returned by useFetch in <script setup> but i am able to access in the html

So I am trying to create a flow where there is a form, when they user modifies the form useFetch is triggered and the results on the page update. things are mostly working well i am able to access the currentPokemon variable within the html and reactivity is working great. The issue is that I am trying to access parts of currentPokemon from within the so that the chart i define will also be reactive.
The graph_data show in the below is in the currentPokemon object, but i cant access it from within <script setup>
<script setup>
import { ref } from 'vue'
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from 'chart.js'
import { Scatter } from 'vue-chartjs'
ChartJS.register(LinearScale, PointElement, LineElement, Tooltip, Legend)
const units = ref('METRIC')
const friction = ref(1)
const payload = ref(1)
const distance = ref(1)
const time = ref(1)
const gearRatio = ref(1)
const motionProfile = ref(0.25)
const conservatism = ref(1.5)
const stage = ref('DEFAULT')
const options = {
responsive: true,
maintainAspectRatio: true
}
const { data: currentPokemon } = await useFetch(`http://localhost:3000/`, {
method: "POST",
body: {
unit_system: units,
motion_profile: motionProfile,
move_time_sec: time,
move_distance_deg: distance,
friction: friction,
payload: payload,
gear_ratio: gearRatio,
safety_factor: conservatism,
be_stage: stage,
manufacturers: ["Bosch"],
motor: "DEFAULT"
}
})
console.log(typeof(currentPokemon))
console.log(currentPokemon)
console.log(currentPokemon.graph_data)
const test = ref(currentPokemon.value)
console.log("test")
console.log(typeof(test))
console.log(test.graph_data)
const data = ref({
datasets: [
{
label: 'Accel Profile 0.25 User',
borderColor: 'red',
backgroundColor: 'red',
borderWidth: 1,
pointRadius: 0,
pointHoverRadius: 5,
// tension: 0,
showLine: true,
fill: false,
data: [
{x: user_graph.x[0], y: user_graph.y[0]},
{x: user_graph.x[1], y: user_graph.y[1]},
{x: user_graph.x[2], y: user_graph.y[2]},
{x: user_graph.x[3], y: user_graph.y[3]}
]
}
]
})
here is the console output
✔ Vite server hmr 6 files in 54.932ms 13:56:25
object 13:56:25
[Vue warn]: Unhandled error during execution of setup function 13:56:25
at <App>
RefImpl { 13:56:25
__v_isShallow: false,
dep: undefined,
__v_isRef: true,
_rawValue: {
motormatch: {
'1': [Object],
'3': [Object],
'5': [Object],
'7': [Object],
'10': [Object]
},
stage_details: { DEFAULT: [Object] },
motioncalcs: {
'0.5': [Object],
'0.33': [Object],
'0.1': [Object],
'0.25 User': [Object]
},
graph_data: {
xlabel: 'Time (s)',
ylabel: 'Velocity (deg/s)',
title: 'Move Profiles',
profiles: [Array]
}
},
_value: {
motormatch: {
'1': [Object],
'3': [Object],
'5': [Object],
'7': [Object],
'10': [Object]
},
stage_details: { DEFAULT: [Object] },
motioncalcs: {
'0.5': [Object],
'0.33': [Object],
'0.1': [Object],
'0.25 User': [Object]
},
graph_data: {
xlabel: 'Time (s)',
ylabel: 'Velocity (deg/s)',
title: 'Move Profiles',
profiles: [Array]
}
}
}
undefined 13:56:25
test 13:56:25
object 13:56:25
undefined
Again the goal is to have the paramater passed to the graph be reactive based on the value of currentPokemon.graph_data. I have tried using let to declare new variables and access graph_data that way, which did allow me to get the value of graph_data but it was no longer reactive.
console.log(typeof(currentPokemon))
let res_data1 = currentPokemon.value
let graph_data1 = res_data1.graph_data
let user_graph = graph_data1.profiles[3]
console.log(user_graph)
addition note, in html {{ currentPokemon.graph_data }} works perfectly and is reactive...
Whenever you use ref or computed the way you access values template vs script differs, in script you must use the value key accessor, in template you omit it because in templates the value key accessor is injected at compilation run-time.
<script setup>
const myVar = ref([]) // Array
console.log(myVar.value.length) // Outputs 0
myVar.value.push('hello')
console.log(myVar.value.length) // Outputs 1
const count = computed(() => myvar.value.length)
myVar.value.push('world')
console.log(count.value) // Outputs 2
</script>
<template>
<div>Total Items: {{ myVar.length }}</div>
<div>Counter: {{ count.length }}</div>
</template>
However it is not the same case when working with nested reactive reference objects which is what you want to use if you are altering inner values of a nested object where you want to react to those nested alterations:
<script setup>
const myObject = reference({
myData: [] // Array
})
console.log(myObject.myData.length) // Outputs 0
myObject.myData.push('hello')
console.log(myObject.myData.length) // Outputs 1
</script>
<template>
<div>Total Items: {{ myObject.myData.length }}</div>
</template>
Not sure if this is the best way to do this... I tried using reactive and a few other methods but this finally worked for me
/ Data pased to scatter plot
const data = computed({
get() {
let res_data1 = currentPokemon.value
let user_graph = res_data1.graph_data.profiles[3]
let dataset = {datasets: [
{label: 'Accel Profile 0.5',
fill: false,
borderColor: 'blue',
backgroundColor: 'blue',
borderWidth: 1,
// pointBackgroundColor: ['#000', '#00bcd6', '#d300d6'],
// pointBorderColor: ['#000', '#00bcd6', '#d300d6'],
pointRadius: 0,
pointHoverRadius: 5,
fill: false,
// tension: 0,
showLine: true,
data: [
{x: 0, y: 0},
{x: 0.5, y: 2},
{x: 0.5, y: 2},
{x: 1, y: 0}]},
{label: 'Accel Profile 0.33',
fill: false,
borderColor: 'orange',
backgroundColor: 'orange',
borderWidth: 1,
pointRadius: 0,
pointHoverRadius: 5,
// tension: 0,
showLine: true,
data: [
{x: 0, y: 0},
{x: 0.33, y: 1.49},
{x: 0.66, y: 1.49},
{x: 1, y: 0}]
},
{
label: 'Accel Profile 0.1',
borderColor: 'green',
backgroundColor: 'green',
borderWidth: 1,
pointRadius: 0,
pointHoverRadius: 5,
// tension: 0,
showLine: true,
fill: false,
data: [
{x: 0, y: 0},
{x: 0.1, y: 1.11},
{x: 0.9, y: 1.11},
{x: 1, y: 0}]
},
{
label: 'Accel Profile 0.25 User',
borderColor: 'red',
backgroundColor: 'red',
borderWidth: 1,
pointRadius: 0,
pointHoverRadius: 5,
// tension: 0,
showLine: true,
fill: false,
data: [
{x: user_graph.x[0], y: user_graph.y[0]},
{x: user_graph.x[1], y: user_graph.y[1]},
{x: user_graph.x[2], y: user_graph.y[2]},
{x: user_graph.x[3], y: user_graph.y[3]}
]
}
]}
return dataset
},
// setter
set(newValue) {
// Note: we are using destructuring assignment syntax here.
[firstName.value, lastName.value] = newValue.split(' ')
}
})

In R how to replicate highchart chart with highcharter package

I need to replicate this chart bellow in my shiny app. But I am struggling to deal with the javascript part Any help would be amazing:
Clock Chart Highchart
This is the javascript code: how do I 'translate' this to R?
Any help/indication to deal with javascript in R would be amazing.
Many many tahnks guys
`/**
* Get the current time
*/
function getNow() {
var now = new Date();
return {
hours: now.getHours() + now.getMinutes() / 60,
minutes: now.getMinutes() * 12 / 60 + now.getSeconds() * 12 / 3600,
seconds: now.getSeconds() * 12 / 60
};
}
/**
* Pad numbers
*/
function pad(number, length) {
// Create an array of the remaining length + 1 and join it with 0's
return new Array((length || 2) + 1 - String(number).length).join(0) + number;
}
var now = getNow();
// Create the chart
Highcharts.chart('container', {
chart: {
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false,
height: '80%'
},
credits: {
enabled: false
},
title: {
text: 'The Highcharts clock'
},
pane: {
background: [{
// default background
}, {
// reflex for supported browsers
backgroundColor: Highcharts.svg ? {
radialGradient: {
cx: 0.5,
cy: -0.4,
r: 1.9
},
stops: [
[0.5, 'rgba(255, 255, 255, 0.2)'],
[0.5, 'rgba(200, 200, 200, 0.2)']
]
} : null
}]
},
yAxis: {
labels: {
distance: -20
},
min: 0,
max: 12,
lineWidth: 0,
showFirstLabel: false,
minorTickInterval: 'auto',
minorTickWidth: 1,
minorTickLength: 5,
minorTickPosition: 'inside',
minorGridLineWidth: 0,
minorTickColor: '#666',
tickInterval: 1,
tickWidth: 2,
tickPosition: 'inside',
tickLength: 10,
tickColor: '#666',
title: {
text: 'Powered by<br/>Highcharts',
style: {
color: '#BBB',
fontWeight: 'normal',
fontSize: '8px',
lineHeight: '10px'
},
y: 10
}
},
tooltip: {
formatter: function () {
return this.series.chart.tooltipText;
}
},
series: [{
data: [{
id: 'hour',
y: now.hours,
dial: {
radius: '60%',
baseWidth: 4,
baseLength: '95%',
rearLength: 0
}
}, {
id: 'minute',
y: now.minutes,
dial: {
baseLength: '95%',
rearLength: 0
}
}, {
id: 'second',
y: now.seconds,
dial: {
radius: '100%',
baseWidth: 1,
rearLength: '20%'
}
}],
animation: false,
dataLabels: {
enabled: false
}
}]
},
// Move
function (chart) {
setInterval(function () {
now = getNow();
if (chart.axes) { // not destroyed
var hour = chart.get('hour'),
minute = chart.get('minute'),
second = chart.get('second'),
// run animation unless we're wrapping around from 59 to 0
animation = now.seconds === 0 ?
false : {
easing: 'easeOutBounce'
};
// Cache the tooltip text
chart.tooltipText =
pad(Math.floor(now.hours), 2) + ':' +
pad(Math.floor(now.minutes * 5), 2) + ':' +
pad(now.seconds * 5, 2);
hour.update(now.hours, true, animation);
minute.update(now.minutes, true, animation);
second.update(now.seconds, true, animation);
}
}, 1000);
});
/**
* Easing function from https://github.com/danro/easing-js/blob/master/easing.js
*/
Math.easeOutBounce = function (pos) {
if ((pos) < (1 / 2.75)) {
return (7.5625 * pos * pos);
}
if (pos < (2 / 2.75)) {
return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
}
if (pos < (2.5 / 2.75)) {
return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
}
return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
};`
This converts that JS into R/JS (you need to collect time in Javascript). I noticed odd vertical lines in the Viewer pane of RStudio when this runs, but these lines don't appear in my browser.
For most calls in JS for highcharter, the function or argument is identical in R. I used lubridate for the time functions in the R code. (Although, you could set the time to static values because the time isn't controlled by R code.)
After creating the graph, I used htmlwidgets::onRender to give add the animation so that it follows actual time.
If you run this without htmlwidgets, this is what you'll see. (Well, you'll see the time on the clock for your local time at the moment you render it.)
library(highcharter)
library(lubridate)
highchart() %>%
hc_chart(type = "gauge", plotBackgroundColor = NULL,
plotBackgroundImage = NULL, plotBorderWidth = 0,
plotShadow = F) %>%
hc_pane(
background = list(
backgroundColor = list(
radialGradient = list(cx = .5, cy = -.4, r = 1.9),
stops = list(
list(.5, "rgba(255, 255, 255, .2)"),
list(.5, "rgba(200, 200, 200, .2)"))
))) %>%
hc_tooltip(enabled = FALSE) %>%
hc_yAxis(
labels = list(distance = -20),
min = 0, max = 12, lineWidth = 0, showFirstLabel = F,
minorTickInterval = "auto", minorTickWidth = 1,
minorTickColor = "#666", tickColor = "#666",
minorTickPosition = "inside", minorGridLineWidth = 0,
tickInterval = 1, tickWidth = 2, tickPosition = "inside",
tickLength = 10) %>%
hc_add_series(
data = list(
list(id = "hour", y = hour(now()), dial = list(
radius = "60%", baseWidth = 4, baseLength = "95%", rearLength = 0)),
list(id = "minute", y = minute(now()), dial = list(
baseLength = "95%", rearLength = 0)),
list(id = "second", y = second(now()), dial = list(
radius = "100%", baseWidth = 1, rearLength = "20%"))),
dataLabels = list(enabled = F)) %>%
htmlwidgets::onRender("
function(el, x) {
chart = $('#' + el.id).highcharts()
$.extend($.easing, {
easeOutElastic: function (x, t, b, c, d) {
var s = 1.70158; var p = 0; var a = c;
if (t == 0) return b; if ((t /= d) == 1) return b+c;
if (!p) p = d*.3;
if (a < Math.abs(c)) { a = c; var s = p/4; }
else var s = p/(2 * Math.PI) * Math.asin (c/a);
return a * Math.pow(2, -10 * t) * Math.sin( (t * d - s) * (2 * Math.PI)/p) + c + b;
}
});
function getNow () {
var now = new Date();
return {
hours: now.getHours() + now.getMinutes() / 60,
minutes: now.getMinutes() * 12 / 60 + now.getSeconds() * 12 / 3600,
seconds: now.getSeconds() * 12 / 60
};
};
setInterval(function () {
var hour = chart.get('hour'),
minute = chart.get('minute'),
second = chart.get('second'),
now = getNow(),
/* run animation unless we're wrapping around from 59 to 0 */
animation = now.seconds == 0 ?
false : {easing: 'easeOutElastic'};
hour.update(now.hours, true, animation);
minute.update(now.minutes, true, animation);
second.update(now.seconds, true, animation);
}, 1000);
}")
In this JS, you'll see some deviation from the original code. I needed to define 'chart'. I did that using the same mechanism that is used to change any highcharter R object into it's HTML rendering: chart = $('#' + el.id).highcharts(). Since the function that sets the interval was originally part of creating the graph, it was an unnamed function. Since we're calling after we render the graph, I dropped that outer function(chart).

Add vertical line for current year in google visualization

I need to add one vertical line in current year (x axis)
Configuration Options in my code follows.
var options = {
title: '*****',
curveType: 'function',
height: 300,
legend: { position: 'bottom' },
chartArea: {width: '80%'},
pointSize:5,
width: 500,
annotation: {
1: {
style: 'line'
}
}
}
Please note I have used annotation for this, but problem is a bit line alone visible. I need a line for full height .
My Full Code :
var options = {
title: 'Chart',
curveType: 'function',
height: 300,
legend: { position: 'bottom' },
chartArea: {width: '80%'},
pointSize:5,
annotation: { height: 300 }
},
chartData = JSON.parse(window._data.chartData), chartPoint = new Array(), i = 0, j = 0;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Google');
data.addColumn('number', 'Yahoo');
data.addColumn({type: 'boolean', role: 'certainty'});
data.addColumn('number', 'Value');
data.addColumn({type: 'boolean', role: 'certainty'});
data.addColumn({type: 'string', role: 'annotation'});
if(Object.keys(chartData.myMap).length > 0) {
$.each(chartData.myMap, function(k, v) {
var val = Math.round(v * 100) / 100;
chartPoint[i] = new Array();
var cDate = new Date();
if(cDate.getFullYear()==k)
chartPoint[i] = [k, val, null, false, null, false,k];
else
chartPoint[i] = [k, val, null, false, null, false,null];
i++;
});
i--;
}
if(Object.keys(chartData.myDataMap).length > 0) {
$.each(chartData.myDataMap, function(k, v) {
var val = Math.round(v * 100) / 100;
var val1 = Math.round(chartData.averageMap[k] * 100) / 100;
if(j==0) {var l = val; j++; } else l = null;
chartPoint[i] = new Array();
chartPoint[i] = [k,l,val,false,val1, false, null];
i++;
});
}
data.addRows(chartPoint);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
It should be like in this page [http://jsfiddle.net/NC37X/][3]
I have three forks from your fiddle that might be along the lines of what you are looking for:
data.addRow(["G", ' ', 'Foo annotation', 8, 1, 0.5]);
http://jsfiddle.net/Balrog30/W2JWa/1/ -
Using annotations, but just placing a space makes nothing print, but still draws a line.
annotations: {
style: 'line',
textStyle: {
opacity: 0
}
}
http://jsfiddle.net/Balrog30/W2JWa/2/ -
Text is still in annotation, but text opacity set to 0 so that text is totally transparent.
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// example copied from Google Visualization API playground,
// modified for category axis annotations
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn({type: 'string', role: 'annotationText'});
data.addColumn('number', 'Cats');
data.addColumn('number', 'Blanket 1');
data.addColumn('number', 'Blanket 2');
data.addRow([{v: 0, f:"A"}, null, null, 1, 1, 0.5]);
data.addRow([{v: 1, f:"B"}, null, null, 2, 0.5, 1]);
data.addRow([{v: 2, f:"C"}, null, null, 4, 1, 0.5]);
data.addRow([{v: 3, f:"D"}, null, null, 8, 0.5, 1]);
data.addRow([{v: 4, f:"E"}, null, null, 7, 1, 0.5]);
data.addRow([{v: 5, f:"F"}, null, null, 7, 0.5, 1]);
data.addRow([{v: 6, f:"G"}, null, null, 8, 1, 0.5]);
data.addRow([{v: 7, f:"H"}, null, null, 4, 0.5, 1]);
data.addRow([{v: 8, f:"I"}, null, null, 2, 1, 0.5]);
data.addRow([{v: 9, f:"J"}, null, null, 3.5, 0.5, 1]);
data.addRow([{v: 10, f:"K"}, null, null, 3, 1, 0.5]);
data.addRow([{v: 11, f:"L"}, null, null, 3.5, 0.5, 1]);
data.addRow([{v: 12, f:"M"}, null, null, 1, 1, 0.5]);
data.addRow([{v: 13, f:"N"}, null, null, 1, 0.5, 1]);
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {
curveType: 'function',
width: 500,
hAxis: {
ticks: [{v:6, f:"G"}, {v:10, f:"K"}]
},
height: 400,
vAxis: {
maxValue: 10
},
annotations: {
style: 'line'
}
});
}
http://jsfiddle.net/Balrog30/W2JWa/3/ -
The third one changes the horizontal axis to a continuous type axis so that I can add ticks. This only works if your x-axis is numberic or date/time in nature. This also kind of messes up your axis labeling because the labeling is tied to the ticks, but I'm not really sure what you're trying to display, so it may or may not matter to you.

Retrieving data from ASP.net sql database into amchart

i am facing quite a problem which is to create the nice graph from http://www.amcharts.com/ but i need to retrieve data from my sql database. But i don't know how to place inside. Please guide me. Below is the way how the graph displayed, but i wanted to work with data from database. Thank you.
<script type="text/javascript">
var chartData = generateChartData();
function generateChartData() {
var chartData = [];
var firstDate = new Date(2012, 0, 1);
firstDate.setDate(firstDate.getDate() - 500);
firstDate.setHours(0, 0, 0, 0);
for (var i = 0; i < 500; i++) {
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
var value = Math.round(Math.random() * (40 + i)) + 100 + i;
chartData.push({
date: newDate,
value: value
});
}
return chartData;
}
AmCharts.makeChart("chartdiv", {
type: "stock",
pathToImages: "../amcharts/images/",
dataSets: [{
color: "#b0de09",
fieldMappings: [{
fromField: "value",
toField: "value"
}],
dataProvider: chartData,
categoryField: "date"
}],
panels: [{
showCategoryAxis: true,
title: "Value",
eraseAll: false,
labels: [{
x: 0,
y: 100,
text: "Click on the pencil icon on top-right to start drawing",
align: "center",
size: 16
}],
stockGraphs: [{
id: "g1",
valueField: "value",
bullet: "round",
bulletColor: "#FFFFFF",
bulletBorderColor: "#00BBCC",
bulletBorderAlpha: 1,
bulletBorderThickness: 2,
bulletSize: 7,
lineThickness: 2,
lineColor: "#00BBCC",
useDataSetColors: false
}],
stockLegend: {
valueTextRegular: " ",
markerType: "none"
},
drawingIconsEnabled: true
}],
chartScrollbarSettings: {
graph: "g1"
},
chartCursorSettings: {
valueBalloonsEnabled: true
},
periodSelector: {
position: "bottom",
periods: [{
period: "DD",
count: 10,
label: "10 days"
}, {
period: "MM",
count: 1,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}]
}
});
</script>
Can you generate this script in your code behind ( using a string builder for example ) then use this
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "'" + YourStringBuild.toString() + "'", true);

d3.js: why don't the columns in my column chart contain the full data?

I am using a slightly modified reusable column chart script from https://gist.github.com/llad/3766585
Works great. However, I was just trying to add some tooltips on hover, that would display additional data from the JSON file for each column, but the additional data is not there. I look in the inspector and just see the two values used to calculate x and y. Is there something obvious in the way the script is written that is not binding the full data set?
The script:
function columnChart() {
var margin = {top: 30, right: 10, bottom: 50, left: 50},
width = 420,
height = 420,
xRoundBands = 0.2,
xValue = function(d) { return d[0]; },
yValue = function(d) { return d[1]; },
xScale = d3.scale.ordinal(),
yScale = d3.scale.linear(),
xFormat = '',
yFormat = '',
yAxis = d3.svg.axis().scale(yScale).orient("left"),
xAxis = d3.svg.axis().scale(xScale);
function chart(selection) {
selection.each(function(data) {
// Convert data to standard representation greedily;
// this is needed for nondeterministic accessors.
data = data.map(function(d, i) {
return [xValue.call(data, d, i), yValue.call(data, d, i)];
});
// Update the x-scale.
xScale
.domain(data.map(function(d) { return d[0];} ))
.rangeRoundBands([0, width - margin.left - margin.right], xRoundBands);
// Update the y-scale.
yScale
.domain(d3.extent(data.map(function(d) { return d[1];} )))
.range([height - margin.top - margin.bottom, 0])
.nice();
// Select the svg element, if it exists.
var svg = d3.select(this).selectAll("svg").data([data]);
// Otherwise, create the skeletal chart.
var gEnter = svg.enter().append("svg").append("g");
gEnter.append("g").attr("class", "bars");
gEnter.append("g").attr("class", "y axis");
gEnter.append("g").attr("class", "x axis");
gEnter.append("g").attr("class", "x axis zero");
// Update the outer dimensions.
svg .attr("width", width)
.attr("height", height);
// Update the inner dimensions.
var g = svg.select("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Update the bars.
var bar = svg.select(".bars").selectAll(".bar").data(data);
bar.enter().append("rect");
bar.exit().remove();
bar.attr("class", function(d, i) { return d[1] < 0 ? "bar negative" : "bar positive"; })
.attr("x", function(d) { return X(d); })
.attr("y", function(d, i) { return d[1] < 0 ? Y0() : Y(d); })
.attr("width", xScale.rangeBand())
.attr("height", function(d, i) { return Math.abs( Y(d) - Y0() ); })
.on("click", function(d, i)
{
d3.selectAll('.bar').classed('fade', true);
d3.select(this).classed("sel", true).classed("fade", false);
})
.on("mouseover", function(d, i)
{
d3.select(this).classed("hover", true);
})
.on("mouseout", function(d, i)
{
d3.select(this).classed("hover", false);
});
// x axis at the bottom of the chart
g.select(".x.axis")
.attr("transform", "translate(0," + (height - margin.top - margin.bottom) + ")")
.call(xAxis.orient("bottom").tickFormat(xFormat));
// zero line
g.select(".x.axis.zero")
.attr("transform", "translate(0," + Y0() + ")")
.call(xAxis.tickFormat("").tickSize(0));
// Update the y-axis.
g.select(".y.axis")
.call(yAxis);
// Horizontal grid
g.insert("g", ".bars")
.attr("class", "grid horizontal")
.call(d3.svg.axis().scale(yScale)
.orient("left")
.tickSize(-(width-margin.left-margin.right), 0, 0)
.tickFormat("")
);
});
}
// The x-accessor for the path generator; xScale ∘ xValue.
function X(d) {
return xScale(d[0]);
}
function Y0() {
return yScale(0);
}
// The x-accessor for the path generator; yScale ∘ yValue.
function Y(d) {
return yScale(d[1]);
}
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return xValue;
xValue = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return yValue;
yValue = _;
return chart;
};
chart.yTickFormat = function(_) {
if (!arguments.length) return yFormat;
yFormat = _;
return chart;
};
chart.xTickFormat = function(_) {
if (!arguments.length) return xFormat;
xFormat = _;
return chart;
};
return chart;
}
The initialization:
function renderGraph(view){
var chartWidth = mainWidth();
var chartHeight = 400;
var parseDate = d3.time.format("%Y-%m-%d").parse;
var xFormat = d3.time.format("%b %e");
var data = [];
var req = $.ajax({
url: '/data/column-data.json',
type: 'GET',
dataType: 'json',
success: function(response) {
data = response;
}
});
$.when(req).done(function() {
d3.select("#columnChart")
.datum(data.widgets)
.call(columnChart()
.width(chartWidth)
.height(chartHeight)
.x(function(d, i) { return parseDate(d[0]); })
.xTickFormat(xFormat)
.y(function(d, i) {
var yData;
if (view === 'thisView'){
yData = d[1];
}else if (view === 'thatView'){
yData = d[2];
}
return yData;
}));
});
}
and the data looks like this:
{ "widgets" : [
["2013-09-15", 1, 66622, 1, 3],
["2013-09-16", 0, 0, 0, 0],
["2013-09-17", 2, 76316, 2, 2],
["2013-09-18", 4, 291244, 8, 12],
["2013-09-19", 1, 74674, 2, 2],
["2013-09-20", 5, 287965, 7, 5],
["2013-09-21", 0, 0, 0, 0],
["2013-09-22", 0, 0, 0, 0],
["2013-09-23", 7, 459249, 15, 22],
["2013-09-24", 2, 317320, 1, 6],
["2013-09-25", 3, 100269, 3, 10],
["2013-09-26", 4, 181080, 8, 4],
["2013-09-27", 1, 38056, 1, 1],
["2013-09-28", 0, 0, 0, 0],
["2013-09-29", 0, 0, 0, 0],
["2013-09-30", 3, 449334, 2, 13],
["2013-10-01", 9, 403929, 5, 15],
["2013-10-02", 4, 222512, 7, 12],
["2013-10-03", 1, 196012, 3, 9],
["2013-10-04", 2, 391716, 2, 8],
["2013-10-05", 0, 0, 0, 0],
["2013-10-06", 0, 0, 0, 0],
["2013-10-07", 4, 260312, 8, 14],
["2013-10-08", 1, 34350, 1, 1],
["2013-10-09", 3, 179067, 9, 18],
["2013-10-10", 2, 124250, 8, 19],
["2013-10-11", 2, 381186, 4, 9],
["2013-10-12", 0, 0, 0, 0],
["2013-10-13", 0, 0, 0, 0],
["2013-10-14", 5, 393400, 11, 17]
]
}
The tooltip should display the full data for any one column. The web inspector shows an array of 2 for each column (I'm expecting an array of 5)
How do I modify the script to bind the full data for each column?
Thanks!
UPDATE:
I still haven't solved this, though #adam-pearce got very close. I've put together a couple jsbin's to help.
A bin for the original script is here: http://jsbin.com/EjugosA/2/edit
and the script with Adam's answer is here: http://jsbin.com/IPoDutA/1/edit
this just has the following commented out:
//data = data.map(function(d, i) {
// return [xValue.call(data, d, i), yValue.call(data, d, i)];
//});
You can see in the second that both x and y axis fail to render, though the full data set I wanted is bound to each bar. The web inspector shows the following error:
'undefined' is not a function (evaluating 'd.getMonth()')" which points to line 8410 in d3.v3.js, in d3_time_formats.
How to I modify this script to get the full data without breaking the axis?
data = data.map(function(d, i) {
return [xValue.call(data, d, i), yValue.call(data, d, i)];
});
Removes everything but the first two columns from data. Looking over the code, I think it would still work if you commented out those three lines.
In responce to your comment:
// x axis at the bottom of the chart
g.select(".x.axis")
.attr("transform", "translate(0," + (height - margin.top - margin.bottom) + ")")
.call(xAxis.orient("bottom"));//.tickFormat(xFormat));
You're trying to print strings as dates which doesn't work without parsing the strings first.

Resources