Show line based on drop down selection - javascript

I am using D3chart. I have four line charts displayed at a time. I need to add a drop down box. Based on the selection I need to display line chart one by one. Could someone help me on this please?
Dropdown will be on the top so once I select option 1 - line 1 should be displayed, option 2 - line 2 and option 3 - line 3 & so on.
My code is here:
<canvas id="myChart" width="100" height="100"></canvas>
<script>
d3.csv("sample-ec.csv").then(makeChart);
function makeChart(players) {
var playerLabels = players.map(function (d) {
return d.Date;
});
var room1Data = players.map(function (d) {
return d.Room1;
});
var room2Data = players.map(function (d) {
return d.Room2;
});
var room3Data = players.map(function (d) {
return d.Room3;
});
var room4Data = players.map(function (d) {
return d.Room4;
});
var chart = new Chart("myChart", {
type: "line",
aspectRatio: 3,
options: {
scales: {
y: {
beginAtZero: true
}
}
},
data: {
labels: playerLabels,
datasets: [
{
label : 'Room 1',
data: room1Data,
backgroundColor: 'rgba(54, 162, 235, 0)',
borderColor:'rgb(54, 162, 235)'
},
{
label : 'Room 2',
data: room2Data,
backgroundColor: 'rgba(75, 192, 192, 0)',
borderColor:'rgb(75, 192, 192)'
},
{
label : 'Room 3',
data: room3Data,
backgroundColor: 'rgba(153, 102, 255, 0)',
borderColor:'rgb(153, 102, 255)'
},
{
label : 'Room 4',
data: room4Data,
backgroundColor: 'rgba(255, 159, 64, 0)',
borderColor:'rgb(255, 159, 64)'
}
]
}
});
}
</script>
</body>
</html>

Related

How to show Label with each line in Chart.js v3? [duplicate]

This question already has an answer here:
How do I show labels along with lines in Chart.js v3? [duplicate]
(1 answer)
Closed last month.
Like this one:
The label property in datasets is not working and shows nothing:
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
The complete code is given below:
<!DOCTYPE html>
<html>
<head>
<title> Example</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.1/chart.min.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
legend: {
display: false
}
}
});
</script>
</body>
</html>
Well if a plugin like https://www.chartjs.org/chartjs-plugin-annotation/2.0.0/ doesn't solve the problem (Check out this answer for a demo), I would write my own specific plugin, that draws on the chart, after rendering was completed (see demo below for details).
And to be on the save side, I would add some padding to the right of the chart, to prevent a cut off, as done in the demo (link to the documentation).
Here a demo, how a very basic plugin could like:
(chart data from the question)
var miniLabelPlugin = {
id: 'miniLabelPlugin',
afterRender: function(chart, args, options) {
const { ctx } = chart;
chart.config.data.datasets.forEach((dataSet, index) => {
let lastPoint = chart.getDatasetMeta(index).data[chart.getDatasetMeta(index).data.length - 1];
let lastValue = dataSet.data[dataSet.data.length -1]
console.info(dataSet.data, lastPoint)
ctx.fillStyle = options.textColor;
ctx.font = options.font;
ctx.fillText(`${lastValue}`, lastPoint.x + options.paddingLeft, lastPoint.y);
});
},
defaults: {
paddingLeft: 10,
font: "10px Arial",
textColor: "black"
}
}
const config ={
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
// here the plugin is added to the chart
plugins: [miniLabelPlugin],
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins:{
legend: {
display: false
},
},
layout: {
padding: {
right: 50
}
}
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
<canvas id="chart" ></canvas>
</div>
For static labels you need to add "animation" key like
import {
Chart,
Sample
} from "chart.js";
import {
map
} from "lodash";
import {
data
} from "../data";
var ctx = document.getElementById("myChart");
const d = map(data, (data, index) => {
return {
data: [data],
backgroundColor: "blue",
pointRadius: 2,
fill: "start"
};
});
const dd = map(data, data => {
return data.y;
});
console.log(dd);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [6, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [5, 20, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}
]
},
options: {
animation: {
onComplete: function() {
const chartInstance = myChart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(
18,
Chart.defaults.global.defaultFontStyle,
Chart.defaults.global.defaultFontFamily
);
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.data.datasets.forEach(function(dataset, i) {
const meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
const data = dataset.data[index];
ctx.fillStyle = "#000";
ctx.fillText(data, bar._model.x, bar._model.y - 2);
});
});
}
},
tooltips: {
enabled: true
},
scales: {
y: {
beginAtZero: true
}
},
legend: {
display: false
}
}
});
Goodluck!

How make border radius for chart area chart.js?

How make border radius for chart area chart.js
I need to make a border radius of 16px for the chart area
Maybe there is a plugin?
I am using chart.js V3.7.
I am using chart.js V3.7
How make border radius for chart area chart.js
I need to make a border radius of 16px for the chart area
Maybe there is a plugin?
I am using chart.js V3.7.
const ctx = document.getElementById('myChart').getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 400)
gradient.addColorStop(0, 'rgba(244, 192, 56, 0.3)')
gradient.addColorStop(0.35, 'rgba(244, 192, 56, 0.3)')
gradient.addColorStop(1, 'rgba(244, 192, 56, 0)');
const plugin = {
id: 'background',
beforeDraw: (chart, args, opts) => {
if (!opts.color) {
return;
}
const {
ctx,
chartArea
} = chart;
ctx.fillStyle = opts.color;
ctx.fillRect(chartArea.left, chartArea.top, chartArea.width, chartArea.height)
}
};
Chart.register(plugin);
var config = {
type: 'line',
data: {
labels: [['05.08', '2021'], ['06.08', '2021'], ['07.08', '2021'], ['08.08', '2021'], ['09.08', '2021'], ['10.08', '2021'], ['11.08', '2021'], ['12.08', '2021'], ['13.08', '2021'], ['14.08', '2021'], ['15.08', '2021']],
datasets: [{
data: [130, 260, 240, 270, 249, 310, 295, 330, 247, 280, 265, 265,],
fill: true,
backgroundColor: gradient,
borderColor: [
'#F4C038',
],
borderWidth: 4,
pointRadius: 6,
pointBackgroundColor: '#272E3B',
pointHoverBorderColor: '#fff',
pointBorderWidth: 4,
pointHoverBorderWidth: 4,
}]
},
options: {
responsive: true,
tension: 0.25,
plugins: {
background: {
color: '#272E3B'
},
legend: {
display: false,
labels: {
font: {
size: 14,
family: "Rubik"
}
}
}
},
scales: {
y: {
grid: {
color: '#3D4554',
borderColor: '#3D4554',
tickColor: 'transparent',
},
ticks: {
padding: 38,
callback: function(value) {
return '$' + value;
},
color: "rgba(255, 255, 255, 0.5)",
font: {
size: 16,
family: "Rubik",
weight: 300
},
}
},
x: {
grid: {
color: '#3D4554',
borderColor: '#3D4554',
tickColor: 'transparent',
},
ticks: {
padding: 16,
color: "rgba(255, 255, 255, 0.5)",
font: {
size: 14,
family: "Rubik",
weight: 300
},
}
}
},
}
};
new Chart(ctx, config);
There is no plugin but you can write your own like so:
const plugin = {
id: 'border',
beforeDraw(chart, args, options) {
const {
ctx,
chartArea: {
left,
top,
width,
height
}
} = chart;
ctx.save();
ctx.strokeStyle = options.color;
ctx.lineWidth = options.width;
ctx.setLineDash(options.dash || []);
ctx.lineDashOffset = options.offset;
ctx.strokeRect(left, top, width, height);
ctx.restore();
}
};
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'pink'
}
]
},
options: {
plugins: {
border: {
color: 'red',
width: 16
}
}
},
plugins: [plugin]
}
const 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.7.0/chart.js"></script>
</body>
To add the border to the chart area in chart.js, we need to use the chartAreaBorder plugin
const chartAreaBorder = {
id: 'chartAreaBorder',
beforeDraw(chart, args, options) {
const {ctx, chartArea: {left, top, width, height}} = chart;
ctx.save();
ctx.strokeStyle = options.borderColor;
ctx.lineWidth = options.borderWidth;
ctx.setLineDash(options.borderDash || []);
ctx.lineDashOffset = options.borderDashOffset;
ctx.strokeRect(left, top, width, height);
ctx.restore();
}
};
Paste the above piece of code before creating your chart and
Then use the following code for creating your chart and border around it,
const ctx = document.getElementById('dynamic-chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'Your_Chart_Type_Here',
data: {
labels:Your_Data_Here,
datasets: [{
label: 'Your Data Here',
data: 'Your_Data_Here,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
plugins:{
chartAreaBorder:{
borderColor:'red',
borderWidth:2,
borderDash:[5,5],
borderDashOffset:2,
}
}
}
},
plugins:[chartAreaBorder]
});
Result is as follow
This Code will give the border to chartArea. I hope this sorted out your problem.

How add the sizes of the slices in the pie chart (at the top) in Chart.js?

I am starting to learn the chart.js library.
I drew a pie chart (like "pie"). When you hover over the slices of the diagram, a number appears in the pop-up window that sets the size of the sector.
new chart(
document.getElementById('diagram_1').getContext('2d'), {
type: 'pie',
data: {
labels: [
'Завершенная задача',
'Новая задача',
'Ошибка выполнения'
],
datasets: [{
label: '# of Votes',
data: [#successful_tasks, #new_tasks, #error_tasks],
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
responsive: false
}
}
)
How can you make this number still displayed at the top, where the sectors are listed (I marked this place with a red circle in the picture)?
I can add the required number to the labels array
...
data: {
labels: [
'Завершенная задача: ' + #successful_tasks,
'Новая задача: ' + #new_tasks,
'Ошибка выполнения: ' + #error_tasks
],
...
But then this number will appear twice in the tooltip
You can use the plugin system for this:
var options = {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
customNumber: {
textColor: 'red',
xOffset: 10,
yOffset: 0,
font: '24px Comic Sans MS'
}
}
},
plugins: [{
id: 'customNumber',
afterDraw: (chart, args, opts) => {
const hoveredSlice = chart._active[0];
const {
ctx,
chartArea: {
right
}
} = chart;
if (!hoveredSlice) {
return;
}
ctx.font = opts.font || '24px verdana, sans-serif'
ctx.fillStyle = opts.textColor || 'black'
const val = chart.data.datasets[hoveredSlice.datasetIndex].data[hoveredSlice.index];
const meassures = ctx.measureText(val);
const height = ctx.measureText('M').width;
ctx.fillText(val, (right - meassures.width - (opts.xOffset || 0)), height + (opts.yOffset || 0))
}
}]
}
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.6.0/chart.js"></script>
</body>
I found the answer. My project is written in CoffeeScript, but I think it would be more useful for the StackOverflow community to post the code in JS.
options: {
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc && arc.custom || {};
var getValueAtIndexOrDefault = Chart.helpers.getValueAtIndexOrDefault;
var arcOpts = chart.options.elements.arc;
var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
var value = chart.config.data.datasets[arc._datasetIndex].data[arc._index];
return {
text: label + ": " + value,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
index: i
};
});
} else {
return [];
}
}
}
}
}

Chart js show data on hovering legend

I have a pie chart and I want to get the number/data of each section of pie chart when hovered upon. I have seen the implementation of this in version 2.9.x but in version 3.x it is not working. I have also tried doing this here:
var pieChartHome = new Chart(
"myChart",
{
type: 'doughnut',
data: {
labels: ['One', 'Two', 'Three'],
datasets: [{
data: [4, 5, 3],
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
borderWidth: 1,
hoverBorderWidth: 3
}]
},
options: {
responsive:false,
plugins: {
legend: {
position:'right',
onHover: (evt, legendItem,legend) => {
const index = pieChartHome.data.labels.indexOf(legendItem.text);
const rect = pieChartHome.canvas.getBoundingClientRect();
const point = pieChartHome.getDatasetMeta(0).data[index].getCenterPoint();
const e = new MouseEvent('mousemove', {
clientX: rect.left + point.x,
clientY: rect.top + point.y
});
pieChartHome.canvas.dispatchEvent(e);
},
}
}
},
}
);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
But this shows me flickering data and not something like this:
Chart.js - show tooltip when hovering on legend
You can set the tooltip via chart.js public methods itself:
var options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
legend: {
position: 'left',
onHover: (evt, item, legend) => {
const chart = legend.chart;
const tooltip = chart.tooltip;
const chartArea = chart.chartArea;
tooltip.setActiveElements([{
datasetIndex: 0,
index: item.index,
}], {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
chart.update();
},
}
}
}
}
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>

Chart.JS - show values on top of points

Good evening,
I'm trying to build a line chart that represents API response time. The problem is that I didn't find any solution in Chart.JS documentation. Is there any native solution or any solution using canvas api?
I want to get the chart looking like this:
Here is the code that I've used to generate the chart
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: hoursArrFirst,
datasets: [{
label: 'First Brand API',
data: timeArrProftit,
borderWidth: 1,
backgroundColor: [
'rgba(255, 99, 132, 0.05)',
'rgba(255, 159, 64, 0.05)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(255, 59, 64, 1)'
]
},{
label: 'Second Brand API',
data: timeArrSecond,
borderWidth: 1,
backgroundColor: [
'rgba(132, 255, 99, 0.05)',
'rgba(64, 255, 159, 0.05)'
],
borderColor: [
'rgba(32,155,99,1)',
'rgba(64,155, 59, 1)'
]
},{
label: 'Third Brand API' ,
data: timeArrThird,
borderWidth: 1,
backgroundColor: [
'rgba(32, 99, 255, 0.05)',
'rgba(64, 59, 255, 0.05)'
],
borderColor: [
'rgba(32, 99, 120, 1)',
'rgba(64, 59, 120, 1)'
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
Call a function during and after animation
var options = {
onAnimationProgress: function() { drawDatasetPointsLabels() },
onAnimationComplete: function() { drawDatasetPointsLabels() }
}
function drawDatasetPointsLabels() {
ctx.font = '.9rem sans-serif';
ctx.fillStyle = '#AAA';
ctx.textAlign="center";
$(Trends.datasets).each(function(idx,dataset){
$(dataset.points).each(function(pdx,pointinfo){
// First dataset is shifted off the scale line.
// Don't write to the canvas for the null placeholder.
if ( pointinfo.value !== null ) {
ctx.fillText(pointinfo.value,pointinfo.x,pointinfo.y - 15);
}
});
});
}

Categories

Resources