I need Define Div(chartContainer1) value in a JavaScript "Var" So that it can be defined in JavaScript Chart Unfortunately am unable to do
HTML:code
<div id="chartContainer" style="height: 300px; width: 100%;">
<div id="chartContainer1">[
{y: 10, legendText:"Wii U", label: "Wii U 10%"},
{y: 13, legendText:"3DS", label: "3DS 13%"},
{y: 18, legendText:"PS3", label: "PS3 18%"},
{y: 20, legendText:"Xbox One", label: "Xbox One 20%"}
];</div>
Chart Code:
I have tried With
var dsp = document.getElementById("mySpan").innerHTML;
var dps = document.getElementById("chartContainer1").innerText;
dataPoints is the place Where i need to define text of Div
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Test title"
},
data: [{
type: "stackedBar100",
dataPoints : dps,
showInLegend: true,
toolTipContent:"{label}"
}],
});
chart.render();
You could use eval to turn it into an object
var dps = eval(document.getElementById("chartContainer1").innerText);
But be warned about using eval Why is using the JavaScript eval function a bad idea?
It is not a good practice storing the data inside a DIV that way, because that JSON data will get displayed on the screen before the chart is rendered.
Please read : https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Instead, if you really want to attach the data along with a particular HTML element, you should store it in a data-something attribute like this:
<div id="chartContainer1" data-content='[
{"y": 10, "legendText":"Wii U", "label": "Wii U 10%"},
{"y": 13, "legendText":"3DS", "label": "3DS 13%"},
{"y": 18, "legendText":"PS3", "label": "PS3 18%"},
{"y": 20, "legendText":"Xbox One", "label": "Xbox One 20%"}
]'></div>
And fetch the data from the attribute for render by:
var dps = JSON.parse(document.getElementById("chartContainer1").dataset.content);
Or classically,
var dps = JSON.parse(document.getElementById("chartContainer1").getAttribute("data-content"));
Related
i'm looking for help with updating the x-axis categories on a Highcharts chart with periodically received data.
The chart is defined in a file called forecastgraph.html. It is loaded to index.php, the webpage where I want it displayed, by means of <?php require("widget/forecastgraph.html"); ?>. The chart renders as expected.
Live data which is handled via a js script (called mqtt.js) that receives incoming mqtt data in json format and using jquery updates various parts of index.php in this way: $("#elementid").html(a.b.c);. I load mqtt.js in the head of index.php using <script src="./js/mqtt.js"></script> This again works flawlessly.
What I am struggling with is how to pass incoming data from mqtt.js to the chart to update it as new data comes in. Specifically, I am trying to update the xAxis categories and the corresponding value pairs. Periodically, mqtt.js receives a new weather forecast and so the xAxis categories need to be updated with the new time period that the forecast applies to and the data needs to be updated to reflect the new high and low temperatures for the respective forecast periods.
The code for the chart is posted below. Any help would be appreciated.
Baobab
<script type="text/javascript">
$(function () {
$('#forecastgraph').highcharts({
chart: {
type: 'columnrange',
backgroundColor: 'rgba(0,0,0,0)',
borderWidth: 0,
margin: [12, 6, 36, 20]
},
title: {
text: null,
},
exporting: {
enabled: false
},
credits: {
enabled: false
},
xAxis: {
categories: [1,2,3,4],
labels: {
y: 30,
style: {
color: 'white',
fontSize: '10px',
fontWeight: 'bold'
}
}
},
yAxis: {
title: {
enabled: false,
x: -14,
},
labels: {
align: 'left'
},
maxPadding: 0.5,
plotLines: [{
value: 10, //normmax
width: 2,
color: '#FF0000'
},{
value: 2, //normmin
width: 2,
color: '#009ACD'
}]
},
tooltip: {
enabled: false
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
style: {
textOutline: 'none'
},
crop: false,
overflow: 'none',
formatter: function () {
var color = this.y === this.point.high ? '#33C4FF' : 'red';
return '<span style="font-size: 12px; font-family:helvetica; font-weight:normal; text-shadow: none; color:' + color + '">' + this.y + '°</span>';
}
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Temperatures',
data: [
[20, -3],
[5, -2],
[6, -2],
[8, -15]
],
color: '#b9deea',
borderColor: '#92cbde',
borderRadius: 4
}]
});
});
</script>
EDIT: Additional Information.
The incoming json data looks like this:
[{
"period": "Monday",
"condition": "Cloudy",
"high_temperature": "7",
"low_temperature": "-2"
"icon_code": "10",
"precip_probability": "20"
}, {
"period": "Tuesday",
"condition": "A mix of sun and cloud",
"high_temperature": "6",
"low_temperature": "-2"
"icon_code": "02",
"precip_probability": "20"
}, {
"period": "Wednesday",
"condition": "A mix of sun and cloud",
"high_temperature": "3",
"low_temperature": "-5"
"icon_code": "02",
"precip_probability": "20"
}, {
"period": "Thursday",
"condition": "A mix of sun and cloud",
"high_temperature": "1",
"low_temperature": "-10"
"icon_code": "02",
"precip_probability": "20"
}]
The function responsible for the incoming json formatted data in the mqtt.js script loaded to index.php handles the incoming data in this way (mqtt.js is started when index.php is loaded):
function onMessageArrived(message) {
console.log("onMessageArrived: " + message.payloadString);
//Env Canada forecast
if (message.destinationName == "myHome/ec/json_data_ec") {
var data = JSON.parse(message.payloadString);
$("#forecast_period_1").html(data[0].period); // update div forecast_period_1 in index.php for debugging purposes and show that data is coming in
forecast_period_1 = (data[0].period); // assign to global var
forecast_period_1_high = (data[0].high_temperature); // global var
forecast_period_1_low = (data[0].low_temperature); // global var
Updating various html elements throughout index.php with the incoming data works great and is stable. What I have attempted to do, but with no success, is to update the chart using the data placed in the global variables (declared as global at he beginning of the script) by the mqtt.js script. In the example above, forecast_period_1 needs to be used as the first of the four xAxis categories and forecast_period_1_high and forecast_period_1_low, to update the respective hi and lo values in the chart's data.
Is this an output that you want to achieve? In the below demo, I wrote a function that takes a high and low temperatures value and next is triggered on the button. The new data is attached to the chart via using the series.update feature.
Demo: https://jsfiddle.net/BlackLabel/he768cz3/
API: https://api.highcharts.com/class-reference/Highcharts.Series#update
I have found a solution for it. First, you have to store the chart in a variable then after you are able to update chart data. Like below
var chart = $('#forecastgraph').highcharts({ ...option })
Update xAxis or series data
// Update xAxis data label
chart.update({
xAxis: {
categories: [1,2,3,4]
}
});
// Update series data
chart.series[0].update({
data: [
[20, -3],
[5, -2],
[6, -2],
[8, -15]
]
});
The code below renders only the last chart from JSON. I want it to append every chart from JSON to a div with a class of reportdiv.
Markup
<div class="reportdiv>
</div>
json
{reportvals:
{
labels:["Apple 25%", "Banana 15%", "Mango 10%", "Orange 35%", "Avocado15% "],
series: [25, 15, 10, 35, 15]
},
{
labels:["Apple 15%", "Banana 25%", "Mango 35%", "Orange 10%", "Avocado15% "],
series: [15, 25, 35, 10, 15]
}
}
JS
for (reportindex = 0; reportindex < settings.json.reportvals.length; reportindex++){
new Chartist.Pie('.reportdiv', {
labels: settings.json.reportvals[reportindex].labels,
series: settings.json.reportvals[reportindex].series
}, options);
}
How can I make my code append all charts to the div?
I can use an ID selector, but I am not sure count of charts are received from the JSON.
I am returning a JSON to my view and I want to parse the date on a line graph, but I am having some issues with adding dates using ChartJS.
This is my JSON format: (can be changed)
[
{ "y": 4, "x": "2017-01-01" },
{ "y": 0, "x": "2017-01-02" },
{ "y": 9, "x": "2017-01-03" },
{ "y": 0, "x": "2017-01-04" },
{ "y": 14, "x": "2017-01-05" }
]
I tried this but keep getting random timestamps
data: {
labels: [],
datasets: [{
data: [{
y: 0,
x: new Date('2017,03,01')
}, {
y: 1,
x: new Date('2017,03,02')
}, {
y: 2,
x: new Date('2017,03,03')
}],
label: "test",
Does anyone have any idea on how to put the correct dates on the x-axis and place the values on the y-axis? Thanks.
There is an error in Date initialization:
new Date('2017,03,01')
should be replaced by
new Date(2017,03,01)
(without quotes), because '2017,03,01' is a string with an invalid date format.
You can initialize a Date object with a string with the following format (the same you have as input):
new Date('2017-03-01')
In order to trasform the json of your input you can write a function like this:
var input = [{"y":4,"x":"2017-01-01"},
{"y":0,"x":"2017-01-02"},
{"y":9,"x":"2017-01-03"},
{"y":0,"x":"2017-01-04"},
{"y":14,"x":"2017-01-05"}];
var data = input.map(function(item) {
return {x: new Date(item["x"]), y: item["y"]};
});
and pass data to your graph.
Use the json data as is, but tell chart.js that the x axis is time. working fiddle
options: {
"scales": {
"xAxes": [{
"type": "time"
}]
}
}
See http://www.chartjs.org/docs/latest/axes/cartesian/time.html for more time axis configuration options. Especially the parser (tick) property, if using various time and date formats.
i am a new when it comes to jquery and javascript but I'm trying learn slowly.What my question is, if i have a json file that looks like
var data= [{"tasknumber":304030,
"date":"2012-05-05",
"operator":"john doe"},
{"tasknumber":23130,
"date":"2012-07-07",
"operator":"john doeeeeeeee"},
{"tasknumber":233330,
"date":"2012-08-08",
"operator":"john doe"}]
and i applied .countBy to it from the underscore library to get a array that looks like this
{"john doe":2,"john doeeeeeeee":1}
so for the next part im using a sample jquery graph outline which i found online
<!DOCTYPE HTML>
<html>
<head>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
I tried a couple ways to call my new array within this part of the code
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
//insert here
]
}
]
but i only get blank screens and undefine when i try and open it.does anyone have any guidance for me on how to call my array within the datapoints?
my data is in a different file called task.json and i gotta call it using
var input=require('./task.json');
const _ = require(`underscore`);
var names=_.countBy(input,'operator');
Lets say, your JSON object is stored in some variable(eg: myObject).
var myObject = {"john doe":2,"john doeeeeeeee":1};
Declare a variable to store dataPoints from your JSON and push dataPoints into your array.
var dps = [];
for(var element in myObject) {
dps.push({label: element, y: myObject[element]});
}
Once you have done this, assign this variable (dps) to dataPoints of CanvasJS chart.
data: [
type: "column",
dataPoints: dps
]
You can see a working example in this fiddle.
Is it possible to have multiple charts inside each other:
Please check js fiddle for "single" and what I would like is to have that as a first one, inside second one and so on...
var data = [
{
label: "title 1",
value: 32,
color: "#444334"
}, {
label: "title 2",
value: 51,
color: "#f0f0f0"
}, {
label: "title 3",
value: 17,
color: "#8ba43a"
}];
Check image attached (sorry about bad graphic)
Thanks.
You can do this with jqplot or chart.js
An example from jsplot:
$(document).ready(function(){
var s1 = [['a',6], ['b',8], ['c',14], ['d',20]];
var s2 = [['a', 8], ['b', 12], ['c', 6], ['d', 9]];
var plot3 = $.jqplot('chart3', [s1, s2], {
seriesDefaults: {
// make this a donut chart.
renderer:$.jqplot.DonutRenderer,
rendererOptions:{
// Donut's can be cut into slices like pies.
sliceMargin: 3,
// Pies and donuts can start at any arbitrary angle.
startAngle: -90,
showDataLabels: true,
// By default, data labels show the percentage of the donut/pie.
// You can show the data 'value' or data 'label' instead.
dataLabels: 'value'
}
}
});
});
According to the jqplot page, it requires minimum of jquery 1.9.1, along with it's main jqplot, plus jqplot pieRenderer/donutRenderer scripts and the jqplot css.
The code above will produce something like this:
You can add another series, which will create a third circle.