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
Related
I am trying to implement this tutorial and could not get it done. https://www.chartjs.org/docs/latest/axes/cartesian/time.html
Input: list of objects with (time,value) attributes. Time is Integer that means unix time in seconds; value is Float.
The tutorial says "Date Adapters. The time scale requires both a date library and a corresponding adapter to be present. Please choose from the available adapters".
Date library, date-fns: https://github.com/date-fns/date-fns
Question 1. how to install/include the date-fns library? The documentation says "npm", but I think it is only for Node.js, but I have a Django project, Ubuntu. If I just download the zip, there is a bunch of files inside.
Adapter, chartjs-adapter-date-fns https://github.com/chartjs/chartjs-adapter-date-fns.
Question 2. how to install the fns adapter? The documentation says "npm", but I have a Django project, Ubuntu. BUT, if I include <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>, I feel it is enough.
Question 3. after installing adapter and date library, how to fix the script below to make the plot work (Time Cartesian Axis)? I think it is all about updating line point["x"] = elem.time; to convert a unix time to some appropriate type.
HTML
<canvas id="myChart"></canvas>
JS
let points = [];
for(let elem of objs) {
point = {};
point["x"] = elem.time;
point["y"] = elem.value;
points.push(point);
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: points,
// Configuration options go here
options: {
responsive: false,
scales: {
x: {
type: 'time',
}
}
}
});
Installing all the 3 required libs can indeed be done using script tags, see live example underneath.
The reason your data doesnt show is because chart.js doesnt expect a data array in the data field. In the data field it expects an object with at least a key for all the datasets which is an array and an optional labels array, but since you are using object format for your data the labels array is not neccesarry.
Each dataset has its own label for the legend and in the dataset object you configure the data array in the data field. See live example:
const options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: 1632664468243,
y: 5
}, {
x: 1632664458143,
y: 10
}],
borderColor: 'pink'
}]
},
options: {
scales: {
x: {
type: 'time'
}
}
}
}
const ctx = document.getElementById('tt').getContext('2d');
new Chart(ctx, options);
<canvas id="tt"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
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();
});
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¤cyPair=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
}),
I have a page with several charts, and I need to be able to add specific options to the exporting context menu for each chart. This is the code I am using:
myChart.options.exporting.buttons.contextButton.menuItems.push({
text: "Custom Option",
onclick: someFunction
});
Unfortunately, this adds the option to every chart, not just the chart myChart references. I'd like to be able to add an option and have it appear on only one chart.
Here is a fiddle which demonstrates: http://jsfiddle.net/4uP5y/2/
Thanks!
To add button use options for chart. Then you can set for each chart different set of options: http://jsfiddle.net/4uP5y/4/
Get default buttons:
var buttons = Highcharts.getOptions().exporting.buttons.contextButton.menuItems;
buttons.push({
text: "Tokyo Only Option",
onclick: HelloWorld
});
And set them for a chart:
exporting: {
buttons: {
contextButton: {
menuItems: buttons // or buttons.slice(0,6)
}
}
},
See the updated fiddle with result : http://jsfiddle.net/4uP5y/3/
You just needed to mark the newYork chart with exporting enabled false, like this :
exporting: {
enabled: false
}
Starting from Paweł Fus answer, I found out a cleaner solution for the general case. The main issue is you need not to mess around with original object and extend it. Instead, you'd be better cloning it. Please note that my solution requires jQuery.
function appendExportButton(mytext, myfunction){
var defaultButtons = Highcharts.getOptions().exporting.buttons; // get default Highchart Export buttons
var myButtons = $.extend(true, {}, defaultButtons);
myButtons.contextButton.menuItems.push({
text: mytext,
onclick: myfunction
});
return {buttons: myButtons};
}
To insert this button in the desired chart, define the chart this way:
var mychart = new Highcharts.Chart({
chart: {
...whatever...
},
plotOptions: {
...whatever...
},
series: {
...whatever...
},
exporting: appendExportButton("Save data in CSV format", saveCSV)
});
In the case of OP problem, this is the line you have to use:
exporting: appendExportButton("Tokyo Only Option", HelloWorld)
JSFiddle
I found another possiblity to add it only to one chart. Add following to the chart where you want to extend the context menu
exporting: {
buttons: {
contextButton: {
menuItems: [
]
}
}
},
.
Now you are able to extend the chart dynamicly with a method like
function (button) {
var userMenu = this.chart.userOptions.exporting.buttons.contextButton.menuItems;
if (userMenu.length === 0) {
var menuItems = Highcharts.getOptions().exporting.buttons.contextButton.menuItems;
for (var itemIndex in menuItems) {
userMenu.push(menuItems[itemIndex]);
}
}
userMenu.push(button);
};
. Where this.chart points to the chart which context menu should be extended
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 ....