Chart.js showing different graphs with select - javascript

basically, I have made a Graph that looks like this Image.
I want to make the Graph update whenever I choose an option ( a location in this example). Any idea how could I go on about this?

It sounds like you need to update the chart data whenever the user selects a value from the dropdown. So, add an event listener to the location selector dropdown element, then replace the chart data with the data for the selected location, then call chart update. That part is very simple. It's explained in the chart.js docs under Updating Charts. https://www.chartjs.org/docs/latest/developers/updates.html
For example, if you had location data in an object and a transformData function to convert it to x/y coordinates, you might do something like this for a line chart:
const defaultLocation = 'munchen';
const chart = new Chart(chartCanvas,
{
type: 'line',
data: transformData(locationData[defaultLocation]),
options: {
animation: false,
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
},
x: {
type: 'timeseries',
},
},
},
});
const locationSelector = document.getElementById("location-selector");
locationSelector.addEventListener('change', ({ target }) => {
chart.data = transformData(locationData[target.value]);
chart.update();
});

Related

Show Labels on Pie pieces instead of Data values Chart.js

I use Chart.js for making charts. I discovered today new plugin for the original Chart.js.
Plugin
After i added <script> tags with the plugin, it applied automatically values to all my charts. It looks great, but it shows number values. How do i make it show labels instead of values on the pieces of the pie? I have found some posts about the subject, but they contain different commands, and i tried all i could but it didn't change anything. Also for the future, tell me please how to turn off showing values for specific chart :)
fillPie()
{
// Three arrays have same length
let labelsArr = []; // Array with some names
let values = []; // Array with values
let randomColor = [];
var ctx = document.getElementById('pie-chart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'pie',
// The data for our dataset
data: {
labels: labelsArr, // I want it to show these labels
datasets: [{
backgroundColor: randomColor,
data: values, // It shows these values
hoverBackgroundColor: "#fba999"
}]
},
// Configuration options go here
options: {
legend: {
display: false
}
}
});
}
You can find the answer in the docs of the plugin:
https://chartjs-plugin-datalabels.netlify.com/guide/formatting.html#custom-labels
options: {
plugins: {
datalabels: {
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
}
}
}
}
The dev simonbrunel explained on GitHub how you can disable the plugin globally or for specific datasets. The following is a quote from the GitHub link:
That should be possible by disabling labels for all datasets via the plugin options at the chart level using the display option, then enable labels per dataset at the dataset level (dataset.datalabels.*):
new Chart('id', {
data: {
datasets: [{
// no datalabels for this dataset
}, {
datalabels: {
// display labels for this specific dataset
display: true
}
}
},
options: {
plugins: {
datalabels: {
// hide datalabels for all datasets
display: false
}
}
}
})
You can also globally disable labels for all charts using:
// Globally disable datalabels
Chart.defaults.global.plugins.datalabels.display = false

Converting Poloniex API Callback JSON into format suitable for Highcharts.Stockchart

I am trying to get JSON from Poloniex's public API method (specifically the returnChartData method) to display chart history of cryptocurrencies against one another into a Highchart Stockchart graph (looking like the demo one here.).
This is part of my JavaScript code to use the Poloniex returnChartData callback, get the JSON from it and implement it into the 'data' segment of the chart. So far it is not working and I can't for the life of me figure out what I need to change.
var poloniexUrl = "https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400";
$.getJSON(poloniexUrl, function(data){
results = data;
});
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'cryptoChart',
backgroundColor: 'white'
},
title: {
text: currentTitle
},
series: [{
data: results,
turboThreshold: 1000
}],
xAxis: {
original: false
},
rangeSelector: {
selected: 1
},
plotOptions: {
line: {
gapSize: 2
}
}
});
Would love any help!
Refer to this live demo: http://jsfiddle.net/kkulig/0f4odg5q/
If you use turboThreshold the points' options need to be given as an integer or an array (Explanation: https://api.highcharts.com/highstock/plotOptions.series.turboThreshold). In your case the format is JSON, so I disabled turboThreshold to prevent Higcharts error 12 (https://www.highcharts.com/errors/12):
turboThreshold: 0
$.getJSON is asynchronous - the best way to make sure that data variable is initialized is using it inside callback function (second argument of getJSON):
$.getJSON(poloniexUrl, function(data) {
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
(...)
The data that you fetch looks like candlestick series - I changed the type of the series:
type: 'candlestick'
Date will be properly understood by Highcharts if it's kept in the x property of JSON object (not date):
data: data.map((p) => {
p.x = p.date;
return p
}),

Accessing a previously drawn plot in javascript/jquery

I draw a plot like this:
var items = $.get("./moonlight_sonata_diameter.data", function(data) {
items = data.split(/\r?\n/).map( pair => pair.split(/\s+/).map(Number) );
$(function () {
plot = $.plot($("#placeholder"),
[ { data: linePoints} ], {
series: {
lines: { show: true }
},
crosshair: { mode: "x" },
grid: { hoverable: true, autoHighlight: false },
yaxis: { min: 0, max: 5 }
});
});
});
Now at a later moment in time, I want to update the crosshair of the plot. However, because it is embedded in so many functions, I don't know how to access it as I am not familiar with jQuery.
Within the script, I can run:
plot.setCrosshair({x: 100})
However, in another script, at another time, there is no object called plot. Is there a way to access it still?
Actually you have put your plot creation code in document ready function and your
plot.setCrosshair({x:100}) is executed just before your plot creation code. so A simple settimeout will do the trick.
just replace
plot.setCrosshair({x: 4})
with
setTimeout(function(){ plot.setCrosshair({x: 41})}, 3000);
and this will work fine. if you call your setCrosshair function after loading the complete dom then you will not need of setTimeout function. I hope this will help and if not then let me know.
Check it at http://plnkr.co/edit/3cMHmzWEIk6c39mblb0Z?p=preview

HighChart HighStock Error: Invalid negative value for <rect>

I'm getting the following errors when I load my view and HighChart chart.
I narrowed it down to the use of the Navigator (timeline focus bar), I'm using it in my chart:
Here is what it looks like, inside of my chartConfig.options if I disable the navigator I won't get those errors, however this is a feature I want to use.
navigator : {
enabled: true,
adaptToUpdatedData: true,
// enabled: false,
// adaptToUpdatedData: false,
series : {
data : vm.navigatorData
}
},
Now for the default data, this is how I create my Array, I don't have data to fill in the chart yet, until the user takes an action:
vm.navigatorData = [];
var count = 0;
// creates a chart with 97 x points all with 0 y value:
_.times(97, function() {
dayHolder.push({
'x': count++,
'y': 0
});
});
I think this is because vm.navigatorData is empty. You should fill this with data before initializing the chart.

Parsing JSON data for Highcharts

I have been going in circles for a few hours with this and have exhausted all the similar stackoverflow threads and also highcharts docs, so hopefully someone can help.
I am trying to plot a pie chart with a gender split. I have worked with line charts before and so had my data in the format for x and y axis, like this:
[{"y":"Mr","x":"145"},{"y":"Miss","x":"43"},{"y":"Mrs","x":"18"},{"y":"Ms","x":"2"}]
This was getting me somewhere, i could tap into the json and pull out the ints but i couldnt for the life of me get the titles associated with the figures...
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
$.each(data_g, function(key_g, val_g) {
obj_g = val_g;
genderChart.series[0].addPoint(parseInt(obj_g.x));
//genderChart.xAxis[0].categories.push(obj_g.y);
});
});
}
I then just called the function genderData as follows:
genderChart = new Highcharts.Chart({
chart: {
renderTo: 'gender',
events: {
load: genderData
}
}
title: {
text: 'Gender Split'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
},
},
series: [{
type: 'pie',
name: 'Gender Split',
data: []
}]
});
So i ended up with an accurate chart but with out the labels, and they would just default to 'slice'...
So close but no cigar ;-)
Soooo i altered my serverside code to return the following format as per the docs :-), now returning the following:
[{"Mr":"145"},{"Miss":"43"},{"Mrs":"18"},{"Ms":"2"}]
This looks pretty much spot on to me, but alas, when i try to accomodate for this on the js code, everything falls apart.
I have been looking at this:
Write JSON parser to format data for pie chart (HighCharts)
but cant get the practice applied here to fit my circumstances.. Can anyone help?
The forms:
[{"name": "Mr", "y": 145}, ...]
or
[["Mr", 145], ...]
will work. Notice the second form is an array of arrays not an array of objects (you were close).
See basic-pie demo (click view options and scroll down to data), series.data docs, and series.addPoint docs for more info.
If you make the server side return the data in one of the two above forms you can just do:
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
genderChart.series[0].setData(data_g, true);
});
}
You can set your points as follows:
genderChart.series[0].addPoint({
name: key_g,
y: val_g
});
By rearranging my Json to have "name" and "y" as the keys i was able to make progress i.e:
[{"name":"Mr","y":"145"},{"name":"Miss","y":"43"},{"name":"Mrs","y":"18"},{"name":"Ms","y":"2"}]
Then by looping through the json data and parsing the "y" value as a int with the function parseInt() in the JS i was able to get my desired result...
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
$.each(data_g, function(key_g, val_g) {
obj_g = val_g;
genderChart.series[0].addPoint({
name: obj_g.name,
y: parseInt(obj_g.y)
});
console.log(obj_g.y)
});
});
}
I know this question has been solved. but the map function for array might be a good choice in these cases, I love map in functional language!
data = [{"y":"Mr","x":"145"},{"y":"Miss","x":"43"},
{"y":"Mrs","x":"18"},{"y":"Ms","x":"2"}];
var series = data.map(function(e){ return parseInt(e.x); });
.... hight chart ....

Categories

Resources