I have a line chart that's created using chart.js. Everything works fine on page load, but when toggle the chart and hover to chart's corners, it shows old charts.
Also here is the live webapp that you can see the behavior.
https://www.batchrank.com/
I tried to fix with update(), destroy and clear however non of them worked.
Thanks a lot for the help,
Here is my code;
var ctx = document.getElementById("chartContainer").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
data: {
label: "data",
datasets: [
{
label: "Mobile Speed Scores",
data: mobileData,
backgroundColor: ["rgba(255, 99, 132, 0.2)"],
borderColor: ["rgba(255, 99, 132, 1)"],
borderWidth: 1
},
{
label: "Desktop Speed Scores",
data: desktopData,
backgroundColor: ["rgba(49, 67, 129, 0.2)"],
borderColor: ["rgba(49, 67, 129, 1)"],
borderWidth: 1
}
]
},
options: {
responsive: true,
title: {
display: true,
text: inspectUrl
},
scales: {
xAxes: [
{
type: "time",
display: true,
scaleLabel: {
display: true,
labelString: "Date"
}
}
],
yAxes: [
{
scaleLabel: {
display: true,
labelString: "value"
}
}
]
}
}
});
myChart.render();
const removeElements = elms => elms.forEach(el => el.remove());
removeElements(document.querySelectorAll(".progress"));
function toogleDataSeries(e) {
e.dataSeries.visible = !(
typeof e.dataSeries.visible === "undefined" || e.dataSeries.visible
);
myChart.destroy();
myChart.render();
}
}
Related
I'm using chart.js v3.2.0 and I want to disable the grid lines and x-axis labels. I've tried various examples from other stack overflow posts but none seem to work.
https://jsfiddle.net/gcp95hjf/1/
html
<div style = "width: 600px; height: 400px;">
<canvas id="chartJSContainer" width="1" height="400"></canvas>
</div>
js
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132,1)'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)'
}
]
},
options: {
scales: {
xAxes: [{
display: false,
ticks: {
display: false //this will remove only the label
}
}],
yAxes: [{
display:false
}]
},
responsive: true,
maintainAspectRatio: false
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
Does anyone know how to do it?
Thanks
Chart.js v3 has multiple breaking changes, one of them is how you define the scales, it is stated in the migration guide and shown in a lot of the examples (https://www.chartjs.org/docs/3.2.1/getting-started/v3-migration.html)
You will have to change scales: { yAxes: [], xAxes: []} to scales: { y: {}, x: {}}
Working fiddle: https://jsfiddle.net/Leelenaleee/r26h71fm/2/
Hide GridLines on Both Axis -
ChartJS v2 (older version) -
scales: {
x: [
{
gridLines: {
display: false,
},
},
],
y: [
{
gridLines: {
display: false,
},
},
],
},
Newer Version ChartJS v3 -
scales: {
x: {
grid: {
display: false,
},
},
y: {
grid: {
display: false,
},
},
},
I am working on one project where i am using Charts.js for showing charts, Here i want to show all bar values by default on top of each bar (Using bar chat), when we hover mouse on that bar it shows value, but is there any was to show that tooltip by default without hover on it
Below fiddle is the example, Here in this fiddle i want to show 60,30,40 as default on bar chart by default without taking hover on it.
Here in above screenshot i have tried to put all the tooltip as by default but as there are 3 charts are used it shows tooltip to all the charts but I want to put tooltip to only bar chart, I know it's bit tricky but there will be some way using which i can resolve my issue.
Please guide me, here is my code snipped of JS
getchart();
function getchart() {
$("#barChart").remove();
const decimals = 3;
$(".chart").append("<canvas id='barChart' width='692' height='346'></canvas>");
var ctx = document.getElementById("barChart");
Chart.pluginService.register({
beforeRender: function(chart) {
if (chart.config.options.showAllTooltips) {
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
console.log(chart);
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
}
chart.options.tooltips.enabled = false;
},
afterDraw: function(chart, easing) {
if (chart.config.options.showAllTooltips) {
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip.update();
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
})
var barChart;
barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['30', '45', '60', '90', '120', '120+'],
datasets: [{
type: 'bar',
label: 'Receivable',
data: [730, 492.5, 120, 4732.5, 2760.85, 0],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}, {
type: 'line',
label: 'Past Due',
data: [1500, 1500, 1500, 1500, 1500, 1500],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}, {
type: 'line',
label: 'Invoice',
data: [1000, 1000, 1000, 1000, 1000, 1000],
backgroundColor: 'rgba(75, 00, 150, 0.2)',
borderColor: 'rgba(75, 00, 150,1)',
borderWidth: 2
}]
},
options: {
scales: {
xAxes: [{
display: true,
stacked: true,
scaleLabel: {
display: true,
labelString: 'Days'
},
}],
yAxes: [{
display: true,
stacked: true,
scaleLabel: {
display: true,
labelString: 'Dollar Amount'
},
ticks: {
beginAtZero: true,
}
}, {
id: 'invoice-amount',
display: false,
stacked: false,
scaleLabel: {
display: false,
labelString: 'Dollar Amount'
},
ticks: {
beginAtZero: true,
}
}]
},
showAllTooltips: true,
}
});
}
I have a (regularly updating) ChartJS line chart as follows, working off of three types of data - prices, dates, and associated more_info - collected from a Django API:
<script>
var myChart
function refresh_graph() {
{% block jquery %}
var chart_endpoint = "{% url 'chart_data' current_id %}"
var defaultData = []
var labels = []
var more_info = []
$.ajax({
method: "GET",
url: chart_endpoint,
success: function(data){
defaultData = data.prices
labels = data.dates
more_info = data.more_info
if(myChart){
myChart.destroy();
}
var ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets : [{
label: 'Price',
data: defaultData,
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
options: {
elements: {
line: {
tension: 0 // disables bezier curves
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1
}
}]
},
animation: {
duration: 0 // general animation time
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 0 // animation duration after a resize
}
})
}
})
setTimeout(refresh_graph, 5000);
{% endblock %}
}
setTimeout(refresh_graph, 0);
</script>
<div>
<canvas id="myChart" width="1000" height="400"></canvas>
</div>
I'm trying to figure out how to make it so that, when the user clicks on or hovers over (I'd be happy with either) one of the data points in the graph (i.e., a price at a date), they'll see the associated more_info.
I'm aware of this using getElementById, but can't figure out how to extend that to a case like this, where I'm not looking to display a label (here: date) and a data point value (here: price), but rather a third value, i.e., more_info.
I'm also aware of this way of using custom tooltips, but also can't figure out how to extend this from the case where I'm simply using tooltipItem.xLabel (date) and tooltipItem.yLabel (price), as opposed to a third, associated value.
Here's a solution using tooltips (ignoring the Ajax from the OP):
var myChart
function refresh_graph() {
var labels = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]
var defaultData = [0.1,0.5,0.3,0.4,0.6,0.8,0.3]
var more_info = ["Monday info", "Tuesday info", "Wednesday info","Thursday info","Friday info","Saturday info","Sunday info"]
if(myChart){
myChart.destroy();
}
var ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Price",
data: defaultData,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 2,
}]
},
options: {
responsive : true,
tooltips : {
callbacks : {
title : function() {
return 'More information:';
},
afterLabel : function(tooltipItem, data) {
return 'Information: ' + more_info[tooltipItem.index];
},
}
},
elements: {
line: {
tension: 0
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1
}
}]
},
animation: {
duration: 0
},
hover: {
animationDuration: 0
},
responsiveAnimationDuration: 0
}
})
setTimeout(refresh_graph, 50000);
}
setTimeout(refresh_graph, 0);
Full codepen with custom tooltip here: https://codepen.io/kh_one/pen/OJJPBpJ.
This is my code
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{{ $nDate }}],
datasets: [{
label: 'All Users',
data: [ {{ $nUser }} ],
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderColor: ['rgba(54, 162, 235, 1)'],
borderWidth: 3,
lineTension: 0,
labelFontSize : '16',
}]
},
options: {
tooltips: {
mode: 'index',
intersect: false,
position: 'nearest'
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
type: 'category',
labelOffset: 10,
stepSize:250,
callback: function(value, index) {
if (value !== 0) return value;
}
},
gridLines:{
drawBorder:false
}
}],
xAxes: [{
gridLines: {
display: false,
},
}],
},
plugins:{
datalabels:{
display:false
}
}
}
});
My output
My Expected Output
How can I able to put/edit custom tooltip in my line chart? I just want to get the exact tooltips in the second picture but I don't have any idea how to fix it? Another thing is my $nDateI only want to show four dates like 8,15,22,29 But when I tried to create a new array label with value of this [" ", " "]; my chart crashed.
You can use custom callback function to render with your own choice html tags and colors, Follow the official documentation link for further guidance.
http://www.chartjs.org/docs/latest/configuration/tooltip.html#external-custom-tooltips
options: {
tooltips: {
enabled: false,
custom: function(tooltipModel) {}
}
}
I have a Pareto chart (using Chart.js Version: 2.0.2) and i need to display values inside of the bars and under the line.
Any help will be very appreciated:
This is the code (hope that it is useful for somebody):
<canvas id="canvas"></canvas>
<script type="text/javascript">
var data = {
labels: ["8","7","9","11","10"],
datasets: [{
type: "line",
label: "Acumulado",
borderColor: "#BA1E14",
backgroundColor: "#BA1E14",
pointBorderWidth: 5,
fill: false,
data: [34.04,57.45,76.60,89.36,100.00],
yAxisID: 'y-axis-2'
},{
type: "bar",
label: "Asistencia",
borderColor: "#56B513",
backgroundColor: "#56B513",
data: [16,11,9,6,5],
yAxisID: 'y-axis-1'
},{
type: "bar",
label: "SoluciĆ³n",
borderColor: "#000FAA",
backgroundColor: "#000FAA",
data: [16,11,9,6,5],
yAxisID: 'y-axis-1'
}]
};
var options = {
scales: {
xAxes: [{
stacked: true,
scaleLabel: {
display: true,
labelString: "Estaciones"
}
}],
yAxes: [{
type: "linear",
position: "left",
id: "y-axis-1",
stacked: true,
ticks: {
suggestedMin: 0
},
scaleLabel: {
display: true,
labelString: "Minutos"
}
},{
type: "linear",
position: "right",
id: "y-axis-2",
ticks: {
suggestedMin: 0,
callback: function(value) {
return value + "%";
}
},
scaleLabel: {
display: true,
labelString: "Porcentaje"
}
}]
}
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
};
</script>
Right now the chart looks like this:
And i need it to look like this:
This is the answer i developed (only in the options object):
var options = {
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
this.chart.config.data.datasets.forEach(function(dataset) {
ctx.font = "20px Arial";
switch (dataset.type) {
case "line":
ctx.fillStyle = "Black";
dataset.metaData.forEach(function(p) {
ctx.fillText(p._chart.config.data.datasets[p._datasetIndex].data[p._index], p._model.x, p._model.y - 20);
});
break;
case "bar":
ctx.fillStyle = "White";
dataset.metaData.forEach(function(p) {
ctx.fillText(p._chart.config.data.datasets[p._datasetIndex].data[p._index], p._model.x, p._model.y + 20);
});
break;
}
});
}
}
...
};
And this is the result:
I think since version 2.6.0 it's possible to Mix ChartTypes, like Bars and Lines
follow the instructions
A short example is 2 DataSet, one is bar type and other line type:
const data = {
labels: [
'January',
'February',
'March',
'April'
],
datasets: [{
type: 'bar',
label: 'Bar Dataset',
data: [10, 20, 30, 40],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)'
}, {
type: 'line',
label: 'Line Dataset',
data: [50, 50, 50, 50],
fill: false,
borderColor: 'rgb(54, 162, 235)'
}]
};
You just have to calculate the Pareto values and put on the Dataset Line Type