Mark X value on Chart Js graph - javascript

I have this chart:
And I want to mark a given X value for the user. For example I want something like this:
The chart code:
var chart = new Chart(document.getElementById("featureChart"), {
type: 'scatter',
data: {
datasets: [{
label: "Benign_Cross_Entropy",
data: customize_date
}]
},
options: {
responsive: true
}
});
How can I do it ? Thanks
Edit: I'm trying to use annotation and i'm not sure what is wrong.
The example beaver gave in the comments looks good
var ann = [1];
var ann_values = ["your data"];
var annotations_array = ann.map(function(date, index) {
return {
type: 'line',
id: 'vline' + index,
mode: 'vertical',
scaleID: 'x-axis-0',
value: date,
borderColor: 'green',
borderWidth: 1,
label: {
enabled: true,
position: "center",
content: ann_values[index]
}
}
});
var chart = new Chart(document.getElementById("featureChart"), {
type: 'scatter',
data: {
datasets: [{
label: "Benign_Cross_Entropy",
data: customize_date,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderJoinStyle: 'miter'
// pointBorderColor: "rgba(75,192,192,1)",
// pointBackgroundColor: "#fff"
}
]
},
options: {
responsive: true,
elements: { point: { radius: 0 } },
annotation: {
drawTime: 'afterDatasetsDraw',
annotations: annotations_array,
}
}
});

Here is the correct usage of annotation plugin:
var ann = [1];
var ann_labels = ["your data"];
var annotations_array = ann.map(function(value, index) {
return {
type: 'line',
id: 'vline' + index,
mode: 'vertical',
scaleID: 'x-axis-0',
value: value,
borderColor: 'red',
borderWidth: 2,
label: {
enabled: true,
position: "center",
content: ann_labels[index]
}
}
});
console.log(annotations_array)
var data = [{
x: 0,
y: 5
}, {
x: 1,
y: 6
}, {
x: 2,
y: 8
}, {
x: 3,
y: 9
}];
var chart = new Chart(document.getElementById("ctx"), {
type: 'scatter',
data: {
datasets: [{
label: "Benign_Cross_Entropy",
data: data,
borderWidth: 2,
showLine: true,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
//borderCapStyle: 'butt',
//borderJoinStyle: 'miter'
// pointBorderColor: "rgba(75,192,192,1)",
// pointBackgroundColor: "#fff"
}]
},
options: {
responsive: true,
//elements: { point: { radius: 0 } },
annotation: {
drawTime: 'afterDatasetsDraw',
annotations: annotations_array,
},
scales: {
xAxes: [{
type: 'linear',
id: 'x-axis-0',
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.5/chartjs-plugin-annotation.min.js"></script>
<canvas id="ctx"></canvas>
Here is a jsfiddle as well: https://jsfiddle.net/beaver71/e3b1Ldms/

Related

Is it possible to make points in a line chart of Chart JS 3.7.0 look like a donut?

the version of Chart JS is 3.7.0
I am looking for a way to make my chart's points look from this:
to something like this:
I found out that there is an option in this library where you can set the points to a certain shape. e.x: pointStyle: 'rectRot' will make the points appearance look like this:
Is there an option or a way to achieve what Im looking for? (Check the second picture).
Thanks in advance!
My chart's javascript:
const data = {
datasets: [
{
backgroundColor: 'black',
borderColor: '#2d84b4',
borderWidth: 2,
data: [
{ x: 'Dec 27', y: 0.204 },
{ x: '01:00', y: 0.234 },
{ x: '02:00', y: 0.274 },
{ x: '03:00', y: 0.234 },
{ x: '04:00', y: 0.304 },
{ x: 'Dec 28', y: 0.506 },
],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: '#2d84b4',
pointHoverBorderColor: '#2d84b4',
},
],
};
const config = {
type: 'line',
data: data,
options: {
animation: {
duration: 0,
},
responsive: true,
maintainAspectRatio: false,
plugins: {
//Do not display legend.
legend: {
display: false,
},
},
scales: {
xAxes: {
stacked: true,
ticks: {
stepSize: 2,
},
grid: {
display: true,
drawBorder: false,
drawOnChartArea: false,
drawTicks: true,
tickLength: 4,
type: 'time',
},
},
yAxes: {
grid: {
drawBorder: false,
drawTicks: false,
},
},
},
elements: {
point: {
radius: 5,
},
},
},
};
// Initialize the Chart.
const myChart = new Chart(document.getElementById('myChart'), config);
window.addEventListener('beforeprint', () => {
myChart.resize(600, 600);
});
window.addEventListener('afterprint', () => {
myChart.resize();
});
//Disable all animations!
myChart.options.animation = false;
myChart.options.animations.colors = false;
myChart.options.animations.x = false;
myChart.options.transitions.active.animation.duration = 0;
The points seemed to work just fine with your transparent background, only on hover you setted a normal background again so the pointHoverBackgroundColor should also be transparent.
To make the point bigger on hover you can use the hoverRadius and to make the line have the same width you can use the pointHoverBorderWidth:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'black',
borderColor: '#2d84b4',
borderWidth: 2,
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBorderColor: '#2d84b4',
hoverRadius: 10,
pointHoverBorderWidth: 2
}]
},
options: {}
}
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.7.0/chart.js"></script>
</body>

Chart.js remove label from legend for if dataset values

I have a chart with multiple datasets. I want the label of a dataset from the legend to not be visible if all the values in a dataset are null. I've found some solutions but they were only working if data was declared in the initial configuration. In my case it is dynamically updated.
Here is the code:
self.initGraph = function () {
ctxWell = document.getElementById("wellChart").getContext('2d');
if (wellChart != undefined)
wellChart.destroy();
wellChart = new Chart(ctxWell, {
type: 'line',
data: {
labels: [],
datasets: [
{
backgroundColor: reportColor.Green,
borderColor: reportColor.Green,
label: 'Motor Frequency Hz',
yAxisID: 'y-axis-2',
data: [],
borderWidth: 1,
pointRadius: 0,
fill: false
},
{
backgroundColor: reportColor.Turquoise,
borderColor: reportColor.Turquoise,
label: 'Pump Discharge Pressure ' + helpers.getListSelectedValue(self.dischargePressureID(), self.pressureList()),
yAxisID: 'y-axis-1',
data: [],
borderWidth: 1,
pointRadius: 0,
fill: false
}
,
]
},
options: {
maintainAspectRatio: false,
animation: {
duration: 0
},
scales: {
yAxes: [
{
id: 'y-axis-1',
// stacked: true,
scaleLabel: {
display: true,
fontSize: 18,
labelString: helpers.getListSelectedValue(self.intakePressureID(), self.pressureList())
},
ticks: {
beginAtZero: true
}
},
{
id: 'y-axis-2',
position: 'right',
display: self.checkAxis(),
scaleLabel: {
display: self.checkAxis(),
fontSize: 18,
labelString: "Hz, " + helpers.getListSelectedValue(self.motorTemperatureID(), self.temperatureList())
},
ticks: {
beginAtZero: true
}
}
]
},
elements: {
line: {
tension: 0.000001
}
},
legend: {
display: true,
onClick: wellChartLegendClick,
}
},
}
});
wellChart.update();
};
self.updateWellDaily = function () {
var chart = wellChart;
chart.data.labels = [];
for (var j = 0; j < chart.data.datasets.length; j++) {
chart.data.datasets[j].data = [];
}
for (var i = 0; i < self.wellResults().length; i++) {
chart.data.labels.push(self.wellResults()[i].reportedTime);
chart.data.datasets[0].data.push(self.wellResults()[i].motorFrequency);
chart.data.datasets[1].data.push(self.wellResults()[i].pumpDischargePressure);
}
chart.update();
};
self.initGraph();
self.updateWellDaily();
The legend filter function can be used for this, if you tell it to hide labels where in the dataset all data is zeros it will update dynamicly, see example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 0],
borderWidth: 1,
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
},
{
label: '# of Counts',
data: [1, 2, 3,4,5,2],
borderWidth: 1,
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}
]
},
options: {
plugins: {
legend: {
labels: {
filter: (legendItem, chartData) => (!chartData.datasets[legendItem.datasetIndex].data.every(item => item === 0))
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("tt").addEventListener("click", () => {
chart.data.datasets[1].data = [0, 0, 0, 0, 0, 0];
chart.update()
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<button id="tt">
change data
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>

How to show xaxis lable o only data point and hide all others?

I have a chartjs line chart requirement where the client is asking to show labels on x axis only if it has a data point. please find his mockup below.
the x-axis is time and here is what I am getting.
how can I achieve this?
here is my config.
options={{
scales: {
xAxes: [
{
distribution: 'linear',
type: "time",
time: {
min: range_min.toDateString(),
max: range_max.toDateString(),
unit: "day",
stepSize: "1",
},
id: 'xAxis',
ticks: {
autoSkip: true,
callback: function (value, index, values) {
return formatDate(new Date(value))
},
}
},
],
},
pan: {
enabled: true,
mode: "x",
speed: 1,
threshold: 1,
},
zoom: {
enabled: true,
drag: true,
sensitivity: 0.5,
mode: "x",
},
annotation: {
annotations: [{
type: 'line',
mode: 'vertical',
scaleID: 'xAxis',
value: 1582229218219,
endValue: 1582229218219,
borderColor: 'rgb(75, 0, 0)',
borderWidth: 4
}]
},
onClick: (event, item) => {
console.log(item)
}
}}
yes this is possible, you can achieve this by using the tick callback like so:
const data = [{
x: 'Red',
y: 10
}, {
x: 'Yellow',
y: 5
}, {
x: 'Orange',
y: 3
}]
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data,
borderWidth: 1,
backgroundColor: 'red',
borderColor: 'red',
fill: false
}]
},
options: {
scales: {
xAxes: [{
ticks: {
callback: (val, y, z, t) => (
data.map(el => el.x).indexOf(val) >= 0 ? val : null
)
}
}]
}
}
}
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/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

Change dot size individually Scatter Chart -- ChartJS

How can I change the size of each different dot in my scatter chart ?
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 15
}, {
x: 10,
y: 5,
}],
pointRadius: 15,
fill: false,
pointHoverRadius: 20
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
}]
}
}
});
After this I want to change each dot size in matter of my ajax response data.
I tried to do this without the star ofc:
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 15
}, {
x: 10,
y: 5,
pointRadius: 15,
*
}],
but with no success.
You should use a bubble chart that accepts the bubble radius in pixels (property r) for each data point.
Please take a look at this sample chart.
you can put each point in a separate series.
this will allow you to assign a separate radius.
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}],
pointRadius: 10,
fill: false,
pointHoverRadius: 20
}, {
label: 'hidden',
data: [{
x: 0,
y: 15,
}],
pointRadius: 20,
fill: false,
pointHoverRadius: 20
}, {
label: 'hidden',
data: [{
x: 10,
y: 5,
}],
pointRadius: 30,
fill: false,
pointHoverRadius: 20
}]
and to prevent multiple legend entries from being displayed,
we can filter out all but one series label.
legend: {
labels: {
filter: function(item, chart) {
return (item.text !== 'hidden');
}
}
},
see following working snippet...
$(document).ready(function() {
var scatterChart = new Chart(document.getElementById('chart').getContext('2d'), {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}],
pointRadius: 10,
fill: false,
pointHoverRadius: 20
}, {
label: 'hidden',
data: [{
x: 0,
y: 15,
}],
pointRadius: 20,
fill: false,
pointHoverRadius: 20
}, {
label: 'hidden',
data: [{
x: 10,
y: 5,
}],
pointRadius: 30,
fill: false,
pointHoverRadius: 20
}]
},
options: {
legend: {
labels: {
filter: function(item, chart) {
return (item.text !== 'hidden');
}
}
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
}]
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="chart"></canvas>
I figured out you can specify an array of values for pointRadius & pointStyle properties :
datasets: [
{
label: "Plan",
data: [10, 15, 5],
pointRadius: [10, 5, 15],
pointStyle: ["rect", "rect", "circle"],
},
],
This way you can specify a size of each dot individually

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

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>

Categories

Resources