Why are the default Chart.js legend boxes transparent rectangles? - javascript

Why are the default Chart.js legend boxes transparent rectangles like these:
How do I make them solid squares like these instead? I've looked through http://www.chartjs.org/docs/latest/configuration/legend.html but can't find anything relevant.
https://jsfiddle.net/askhflajsf/7yped1d5/ (uses the latest master branch build)
var barChartData = {
labels: ["2013-03-09", "2013-03-16", "2013-03-23", "2013-03-30", "2013-04-06"],
datasets: [{
borderColor: "#3e95cd",
data: [10943, 29649, 6444, 2330, 36694],
fill: false,
borderWidth: 2
},
{
borderColor: "#ff3300",
data: [9283, 1251, 6416, 2374, 9182],
fill: false,
borderWidth: 2
}]
};
Chart.defaults.global.defaultFontFamily = "'Comic Sans MS'";
// Disable pointers
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hoverRadius = 0;
var ctx = document.getElementById("bar-chart").getContext("2d");
new Chart(ctx, {
type: 'line',
data: barChartData,
options: {
responsive: true,
legend: {
display: true,
position: "right"
},
title: {
display: false
},
scales: {
xAxes: [{
type: "time",
ticks: {
minRotation: 90
}
}]
}
}
});
<script src="http://www.chartjs.org/dist/master/Chart.bundle.min.js"></script>
<canvas id="bar-chart"></canvas>

This is because you haven't set the backgroundColor property for your datasets (which is responsible for the legend­'s fill color).
datasets: [{
backgroundColor: "#3e95cd",
borderColor: "#3e95cd",
data: [10943, 29649, 6444, 2330, 36694],
fill: false,
borderWidth: 2
}, {
backgroundColor: "#ff3300",
borderColor: "#ff3300",
data: [9283, 1251, 6416, 2374, 9182],
fill: false,
borderWidth: 2
}]
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var barChartData = {
labels: ["2013-03-09", "2013-03-16", "2013-03-23", "2013-03-30", "2013-04-06"],
datasets: [{
backgroundColor: "#3e95cd",
borderColor: "#3e95cd",
data: [10943, 29649, 6444, 2330, 36694],
fill: false,
borderWidth: 2
}, {
backgroundColor: "#ff3300",
borderColor: "#ff3300",
data: [9283, 1251, 6416, 2374, 9182],
fill: false,
borderWidth: 2
}]
};
Chart.defaults.global.defaultFontFamily = "'Comic Sans MS'";
// Disable pointers
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hoverRadius = 0;
var ctx = document.getElementById("bar-chart").getContext("2d");
new Chart(ctx, {
type: 'line',
data: barChartData,
options: {
responsive: true,
legend: {
display: true,
position: "right"
},
title: {
display: false
},
scales: {
xAxes: [{
type: "time",
ticks: {
minRotation: 90
}
}]
}
}
});
<script src="http://www.chartjs.org/dist/master/Chart.bundle.min.js"></script>
<canvas id="bar-chart"></canvas>

Related

Smaller scale for volume dataset in Chart JS

I'm graphing some stocks data and I wanted to put the volume in a smaller gray bar dataset at the bottom, like in Yahoo Finance.
What I want:
The small grey dataset is at the bottom.
What I get:
Three different Y scales and the size of the volume dataset is the same a the other.
My code:
When I create the chart:
new Chart(context, {
type: 'line',
data: {
labels: timestamps.map(n =>
(new Date(n * 1000)).toLocaleString()
),
datasets: [
dataset,
vdataset
]
},
options: {
maintainAspectRatio: false,
scales: {
xAxis: {
// type: 'time'
ticks: {
//autoSkip: true,
maxTicksLimit: 10
}
},
yAxes: [{
id: 'volume',
display: false
}],
y: {
beginAtZero: false
},
},
animation: {
duration: 0
},
plugins: {
autocolors: false,
annotation: {
annotations
}
},
tooltips: {
mode: 'nearest'
},
hover: {
intersect: false
}
}
});
The volume dataset:
{
type: 'bar',
label: `Volume`,
data: ...,
backgroundColor: 'transparent',
borderColor: 'grey',
fill: 'origin',
pointRadius: 0,
borderWidth: 2,
yAxisID: 'volume'
}
you need to give every dataset a yAxisID and then you should name your axis with that id like this:
Data:
var data = {
labels: labels,
datasets: [{
label: 'My First Dataset',
data: generateTestSeries(),
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1,
yAxisID: "something",
},
{
label: 'My Second Dataset',
data: generateTestSeries(),
fill: false,
borderColor: 'rgb(182, 50, 192)',
tension: 0.1,
yAxisID: "volume",
},
]
};
Scales:
scales: {
volume: {
axis: "y",
min: -80,
max: 60,
position: 'right',
},
something: {
axis: "y",
min: -20,
max: 70,
position: 'left',
}
}
Also you shouldn't have the list yAxes, that was how axes were defined in chartjs 2.x
Here is a fiddle to see this in use: JSFiddle
edit: If you want an invisible axis just set display to false as seen in the now updated Fiddle.

How do you set x and y axis and Title for a line chart using charts.js?

This is using charts.js. This code only makes the line graph but the title, x axis and y axis does not show. I want to add title, and the names for those 2 axis onto the graph. what is wrong and how do you fix it? I also want to make the y axis to start from 0 and up.
async function chartDisplay() {
await getData1();
await getData2();
const ctx = document.getElementById('chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: xLabels,
datasets: [{
data: ratingDataI,
label: "data1",
borderColor: "#3E95CD",
fill: false
},
{
data: ratingDataA,
label: "data2",
borderColor: "#3E95CD",
fill: false
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'label',
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
x: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Dates'
}
}],
y: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
});
}
the x and y should not be arrays but objects, also the scaleLabel prop is called title now. For all the changes please read the migration guide (https://www.chartjs.org/docs/master/getting-started/v3-migration.html)
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'yAxis'
}
},
x: {
title: {
display: true,
text: 'xAxis'
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

Is it possible to show labels for all lines?

Basically I have chartJS based line chart, with two lines. X axis has dates, and Y axes has price.
There is two lines (one for average price and one for minimum price).
So I was wondering, if it is at all possible to so that lets say I hover over a point for minimum price, the average price point's label pops up as well, and vice versa.
Or if that is not possible, maybe it is possible to make it so each label contains both values (the min and average price for that particular day).
Here is the code, I have so far:
var ctx = document.getElementById('price-history').getContext('2d');
ctx.height = 150;
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: <?= json_encode($priceChangeData['labels']); ?>,
datasets: [
{
label: 'Minimali kaina',
backgroundColor: 'rgb(64, 127, 178)',
borderColor: 'rgb(64, 127, 178)',
borderWidth: 1,
data: <?= json_encode($priceChangeData['line']['price_min']); ?>,
fill: false
},
{
label: 'Vidutinė kaina',
backgroundColor: '#686868',
borderColor: '#686868',
borderWidth: 1,
data: <?= json_encode($priceChangeData['line']['price_avg']); ?>,
fill: false
}
],
},
options: {
responsive: true,
layout: {
padding: {
left: 20,
right: 15
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: false,
labelString: 'Data'
}
}],
yAxes: [{
display: true,
stacked: false,
scaleLabel: {
display: false,
labelString: 'Kaina'
}
}]
}
}
});
I am assuming you are talking about the tooltip­'s label. In that case, you can set tooltips mode to index in your chart­'s options config, like so :
options: {
tooltips: {
mode: 'index'
},
...
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var ctx = document.getElementById('price-history').getContext('2d');
ctx.height = 150;
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'], //<?= json_encode($priceChangeData['labels']); ?>,
datasets: [{
label: 'Minimali kaina',
backgroundColor: 'rgb(64, 127, 178)',
borderColor: 'rgb(64, 127, 178)',
borderWidth: 1,
data: [3, 1, 4, 2, 5], //<?= json_encode($priceChangeData['line']['price_min']); ?>,
fill: false
}, {
label: 'Vidutinė kaina',
backgroundColor: '#686868',
borderColor: '#686868',
borderWidth: 1,
data: [2, 4, 1, 5, 3], //<?= json_encode($priceChangeData['line']['price_avg']); ?>,
fill: false
}],
},
options: {
responsive: true,
tooltips: {
mode: 'index'
},
layout: {
padding: {
left: 20,
right: 15
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: false,
labelString: 'Data'
}
}],
yAxes: [{
display: true,
stacked: false,
scaleLabel: {
display: false,
labelString: 'Kaina'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="price-history"></canvas>

Char.js Interpolation linear

i'm trying to draw functions with Chart.js
I have a problem with my draw let's see :
here
This is the 'x' function and the line isn't straight
I don't know if it's a problem of resolution or of interpolation
So here is my chart :
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
borderWidth:2,
pointRadius :0,
borderColor: 'rgba(0, 0, 255, 1)',
label: 'Scatter Dataset',
data: JSON.parse(data),
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
},
pan: {
enabled: true,
mode: 'xy'
},
zoom: {
enabled: true,
mode: 'xy',
},
responsive: true,
maintainAspectRatio: true,
}
});
Thx guys
The problem is how chart.js is drawing the small line segments between data points. Here is a fiddle that animates a full opacity line over top of a lighter line. The second line is growing at a step=1 while the lighter line is nice and straight [{x:-100,y:-100},{x:100,y:100}]. If you change to step=10 you will see the line fill in straight.
In the code below (or in the fiddle) you can play around with changing the borderWidth, borderColor, and opacity. I tried adding borderCapStyle: 'round' and borderJoinStyle: 'round', but neither seemed to have much effect.
var ctx = document.getElementById("test").getContext("2d");
var i = -100;
var data = [{x: i, y: i}];
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
borderWidth: 2,
pointRadius: 0,
borderColor: 'rgba(0, 0, 255, 1)',
label: 'Scatter Dataset 1',
data: data,
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}, {
borderWidth: 2,
pointRadius: 0,
borderColor: 'rgba(0, 0, 255, 0.4)',
label: 'Scatter Dataset 2',
data: [{x:-100,y:-100},{x:100,y:100}],
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
},
pan: {
enabled: true,
mode: 'xy'
},
zoom: {
enabled: true,
mode: 'xy',
},
responsive: true,
maintainAspectRatio: true,
}
});
var step = 1;
var intervalId = setInterval(function() {
i += step;
if (i <= 100) {
scatterChart.data.datasets[0].data.push({x:i,y:i});
scatterChart.update();
} else {
clearInterval(intervalId);
}
}, 200);
and
<canvas id="test" width="400" height="300"></canvas>

Display values in Pareto chart using Chart.js 2.0.2

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

Categories

Resources