How to put function in ChartJS data structures? - javascript

I'm making a website with one graph that use ChartJS library. This chart display, on the website, all of the data available as default.
My goal is to let the visitors to choose a different number of data of the graph. So, I did one button at the top of the chart which, when a visitor click on it, must change the number of data displayed.
The problem is that ChartJS use a JSON object and I not succeed configure different behaviors in it.
...
datasets: [
{
label: "Exemple",
data: [
{ x: "Day1", y: 0 },
{ x: "Day2", y: 1 },
{ x: "Day3", y: 2 },
{ x: "Day4", y: 3 },
{ x: "Day5", y: 4 },
....
],
...
I tried to put an event on it, like :
data: mybutton.addEventListener("click", () => {
[{x: "Day1", y: 0}]
},
A function, like :
data: myFunction(),
Even a variable with function into, like :
const myData = () => {
// function
}
data: myData,
Or an If else.
Nothing worked... Do you any idea ?

I found the solution by myself.
I put the JSON object in a function, put an AddEventListener("click", function()), targeted the part of the JSON to modify and added an update() at the end.
function chartFunction() {
....
// data before
datasets: [
{
label: "Exemple",
data: [
{ x: "Day1", y: 0 },
.....
button.addEventListener("click", () => {
(myChart.data.datasets[0].data = [...]).myChart.update();
});
};
chartFunction();

Related

C3 creating a bar chart with categorical JSON data

How do you specify the x-axis labels for a C3 bar chart with data loaded via JSON? I don't see anything in the docs and the closest I found was this but it only gives an example for data specified in column format, whereas I have data specified in JSON format like in this example
My attempt:
const chart = c3.generate({
data: {
// x: "title",
json: bookData,
type: "bar",
keys: {
value: ["count"]
}
},
axis: {
x: {
tick: {
values: labels,
rotate: 90,
},
type: "category",
}
},
bindto: "#book-title-histogram",
});
By uncommenting x: "title" it leads to the plot to no longer be visible. With that line commented out, the axis is simply blank.
EDIT: bookData is an array with each element having keys count and title
Looks like mapping your data works.
const bookData = [{
count: 3,
title: 'The Foutainhead'
},{
count: 4,
title: 'Fight Club'
},{
count: 2,
title: 'Ender\'s Game'
}]
const titles = bookData.map((obj) => {
return obj.title
})
const counts = bookData.map((obj) => {
return obj.count
})
console.log(titles)
const chart = c3.generate({
data: {
x: 'title',
y: 'count',
json: {
title: titles,
data: counts,
},
type: "bar",
},
axis: {
x: {
tick: {
count: bookData.length,
rotate: 45,
},
type: "category",
}
},
bindto: "#book-title-histogram",
});

How to wrap this behavior in a plugin?

Currently I have a request to have a Bullet Chart with two targets (min and max).
To do it I am simply using a normal Bullet Chart with a Scatter series to draw the other target. I would like to wrap this behavior inside the bullet chart, so it would have something like the following options:
series: [{
data: [{
y: 275,
target: 250,
minTarget: 100
}]
},
And then, on the wrap, I would get this minTarget and make a scatter plot automatically. How can I do it?
Here's the fiddle I have so far: http://jsfiddle.net/gwkxd02p/
I do not think that render is a good method to add another series - anyway, you can try to do it like this:
Highcharts.wrap(Highcharts.seriesTypes.bullet.prototype, 'render', function(p) {
if (!this.hasRendered) {
const scatterData = this.points
.map(({ x, y, options }) => ({
x,
y: options.minTarget !== undefined ? options.minTarget : null
}))
if (scatterData.length) {
const scatter = this.chart.addSeries({
type: 'scatter',
data: scatterData,
marker: {
symbol: 'line',
lineWidth: 3,
radius: 8,
lineColor: '#000'
}
}, false)
scatter.translate()
scatter.render()
}
}
p.call(this)
})
And data for bullet:
series: [{
data: [{
y: 275,
target: 250,
minTarget: 100
}, {
y: 100,
target: 50
}, {
y: 500,
target: 600,
minTarget: 20
}]
live example: http://jsfiddle.net/n4p0ezzw/
I think that the better place is bullet's init method but in that method the points do not exist yet - so you would have to match the x values (if it is needed) on your own.
My suggestion is - do not wrap Highcharts if you don't have to. A better (simpler, safer, cleaner, easier to debug, it does not change Highcharts internal code) practice would be to wrap the Highcharts constructor in a function and parse the options inside it and then call the chart constructor with new options, like this:
function customBullet(container, options) {
const newOptions = {} // parse options, check for minTarget, etc. and create new options
return Highcharts.chart(container, newOptions)
}

Chartjs fiddle not working

I'm completely new to JSFiddle. I'm currently trying to get a scatter chart to show up but nothing is displaying. Can anyone point me in the right direction?
Here's the Fiddle: http://jsfiddle.net/roka545/qf8ejytt/
//Get context with jQuery - using jQuery's .get() method.
let canvas = <HTMLCanvasElement>document.getElementById("myChart");
let ctx = canvas.getContext("2d");
let xAxisMin: number = 4;
let xAxisMax: number = 7;
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
You need to add a link to the actual source such as:
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js
In the external resources, then press plus button.
See here:
http://jsfiddle.net/r7ahsn15/
Did you look at the console? It says:
And that's because:
Meaning that the link you provided was over http rather than https as jsfiddle. Browsers don't allow that kind of requests (http inside https sites) for security reasons.
Nevertheless, I'm searching for a working example and it seems that all the chart.js fiddles are having the same error:
https://jsfiddle.net/uc25erpc/
https://jsfiddle.net/achudars/NXPhL/
http://fiddle.jshell.net/leighking2/898kzyp7/

How to fill data dynamically in Highchart

I'm using below code to display bar chart, I don't know how to populate value dynamically in name and y field. I've name and y data in javascript array.
var productsName = [Laptop,Photoframe,PuzzleBox];
var productPrintCount = [56,24,10]
I don't want to hardcode name and y value in chart, I want to populate dynamically, can someone help how can I put these value in below chart?
JSFiddle
data: [{
name: 'Laptop',
y: 56
}, {
name: 'Photoframe',
y: 24
}, {
name: 'PuzzleBox',
y: 10
}]
var productsName = ['Laptop', 'Photoframe', 'PuzzleBox'],
productPrintCount = [56,24,10],
mappingDataFn = function () {
var resultData = [];
$.each(productsName, function (key, value) {
resultData.push({
'name': value,
'y': productPrintCount[key]
});
});
return resultData;
};
...
series: [{
name: 'Brands',
colorByPoint: true,
data: mappingDataFn()
}]
The idea:
mapping the data from a function.
here the jsfiddle

Cannot read property "getPropertyValue" of null in xChart

I am trying to use d3-based charting library xChart to create a graph module in my webapp. I am just using the example data provided by the xChart documentation, and I get this error every time I try to create the chart:
Uncaught TypeError: Cannot read property 'getPropertyValue' of null
The error is on line 666 (lol) of d3.js in the getComputedStyle method.
if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name);
My JavaScript is as follows:
var data = {
xScale: "ordinal",
yScale: "linear",
main: [
{
className: ".pizza",
data: [
{
x: "Pepperoni",
y: 4
}, {
x: "Cheese",
y: 8
}
]
}, {
className: ".pizza",
data: [
{
x: "Pepperoni",
y: 6
}, {
x: "Cheese",
y: 5
}
]
}
]
};
var myChart = new xChart('bar', data, '#graph-figure');
And my HTML is
<figure id="graph-figure"></figure>
Can anyone help me out with this?
You are most likely executing your javascript before the dom is ready. You can either wrap your javascript in a window.onload function...
window.onload = function(){
// your code here
}
Or include your <script> or inline code right before your closing </body> tag.

Categories

Resources