Draw horizontal line on chart in chart.js on v2 - javascript

I have drawn a line chart using chart.js. For the labels and datasets i am getting values from the database. I am new to chart.js and its very powerful library, yet i am unable to completely understand it. I want to draw multiples horizontal lines. Like where if mean of dataset, standard deviation and min and max. I have tried the question here in stackoverflow but these are giving errors or may be i am not able to understand the working. This is my chart.js code
function display_graph(id, label, data) {
var ctx = document.getElementById(id);
var data = {
labels: data.labels,
datasets: [
{
label: label,
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderWidth: 1,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: data.assay_value,
spanGaps: false
}
]
};
//options
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: label,
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
}
};
var Blanks_Chart=null;
Blanks_Chart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});}

You could use the chart.js annotation plugin to easily draw lines on your chart without having to mess with rendering pixels in your canvas manually (the old approach that is giving you errors). Note, the plugin is created/supported by the same team as chart.js and is mentioned in the chart.js docs.
Here is an example codepen demonstrating creating a line on a chart.
Once you add the plugin, you simply just set annotation properties in your chart config. Here is an example.
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February"],
datasets: [{
label: 'Dataset 1',
borderColor: window.chartColors.blue,
borderWidth: 2,
fill: false,
data: [2, 10]
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Draw Line On Chart'
},
tooltips: {
mode: 'index',
intersect: true
},
annotation: {
annotations: [{
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: 5,
borderColor: 'rgb(75, 192, 192)',
borderWidth: 4,
label: {
enabled: false,
content: 'Test label'
}
}]
}
}
});

if you want to draw threshold line,easiest way is that using mixed line chart.
Note: Make an array filled with threshold value and the length should be same as your dataset.
var datasets = [1, 2, 3];
var ctx = document.getElementById('chart').getContext('2d');
var thresholdValue = 2;
var thresholdHighArray = new Array(datasets.length).fill(thresholdValue);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [
{datasets}, thresholdHighArray]
},
options: {
responsive: true,
legend: {
position: 'bottom',
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Readings'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Reading ( °C )'
}
}]
},
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
borderColor: "red",
label: {
content: "",
enabled: true,
position: "top"
}
}
]
}
});
};

If you are using the NPM package chartjs-plugin-annotation.js, the important thing - which you may forget, is to register the plugin.
So first of all you installed the npm packages (here for React):
npm i react-chartjs-2 (depends on your framework)
npm i chartjs-plugin-annotation (always required)
See Vue.js or Angular for their framework depending packages.
Option 1: Global plugin registration
import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';
import * as ChartAnnotation from 'chartjs-plugin-annotation';
Chart.plugins.register([ChartAnnotation]); // Global
// ...
render() {
return (
<Line data={chartData} options={chartOpts} />
)
}
Option 2: Per chart plugin registration
import { Line } from 'react-chartjs-2';
import * as ChartAnnotation from 'chartjs-plugin-annotation';
// ...
render() {
return (
{/* per chart */}
<Line data={chartData} options={chartOpts} plugins={[ChartAnnotation]} />
)
}
chartData is equivalent to the data: { section and chartOpts to options: { from jordanwillis answer. See this github post for further information.
There are many other plugins available for chart.js.

Here's an example of getting it working in a Rails view if you're using it with the Chartkick gem:
<%=
line_chart profit_per_day_chart_path(staff), xtitle: 'Day', ytitle: 'Profit',
library: {
annotation: {
annotations: [
{
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: 20,
label: {
content: 'My Horizontal Line',
enabled: true
}
}
]
}
}
%>
Ensure that you've registered the chartjs-plugin-annotation.js plugin with Chart.js first:
import ChartAnnotationsPlugin from 'chartjs-plugin-annotation';
Chart.plugins.register(ChartAnnotationsPlugin);

Related

ChartJs hiding odd index values on x-axes/labels values

["06月10日","06月13日","06月14日","06月15日","06月16日","06月17日","06月20日","06月21日","06月22日","06月23日","06月24日","06月27日","06月28日","06月29日","06月30日","07月01日","07月04日","07月05日","07月06日","07月07日","07月08日","07月11日","07月12日","07月13日","07月14日","07月15日","07月19日","07月20日","07月21日","07月22日","07月25日","07月26日","07月27日","07月28日","07月29日","08月01日","08月02日","08月03日","08月04日","08月05日","08月08日","08月09日","08月10日","08月12日","08月15日","08月16日","08月17日"]
above are all the labels that I want to show on the graph but it hiding all the odd index values from the graph only showing even index values on the graph from the above list.
see the graph it missing some labels.
if you see the order all the even number index values are displayed and odd are hidden..
This is all my chart code...
const data = {
labels: dates,
datasets: [{
type: 'line',
label: 'Line graph',
data: line,
fill: false,
borderColor: '#ff5252',
backgroundColor: '#ff5252',
yAxisID: 'y-axis-a',
lineTension: 0.1,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderWidth: 1,
pointHoverRadius: 4,
pointRadius: 5,
pointHitRadius: 10,
},{
type: 'bar',
label: 'Bar graph',
data: diff,
borderColor: colors,
backgroundColor: colors,
borderWidth: 2,
pointRadius: 5,
pointBorderWidth: 1,
pointHoverRadius: 7,
pointHoverBorderWidth: 2,
fill: true,
showLabelBackdrop:true,
},]
};
const config = {
type:"scatter",
data: data,
options: {
legend: {
display: false
},
responsive: false,
scales: {
y: {
display:false,
beginAtZero: true,
ticks: {
color: "#ffffff",
font: {
size: 14,
},
},
},
},
plugins: {
labels: {
ticks:{
font: {
size: 22
},
color: "#ffffff",
}
},
title: {
display: true,
text: title,
padding: {
top: 10,
bottom: 30,
},
font: {
size: 22,
},
color: "#ffffff"
}
}
}
};
const ctx = document.querySelector(`#chart${index+1}`).getContext('2d');
const myChart = new Chart(ctx, config)
I have also tried..
x:{ticks:{autoSkip:false}}
when I do this it changes my label to numbers..
when you are using the type:"scatter",
Scatter charts are based on basic line charts with the x axis changed to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 4 pointslink for charts scatter charts
when you are not defining the values with x and y then used the x-axis and y-axis as linear and then you can manipulate the x-axes for both line and bar..if you will not provide the chart_type in config it will take axes as linear
you can
xAxisID: 'x-axis-bar',
xAxisID: 'x-axis-line',
and then hide the 1 x-axis and autoSkip=False it will show your all values.
I am attaching the all code below..
const data = {
labels: dates,
datasets: [{
type: 'line',
label: 'Line graph',
data: line,
fill: false,
borderColor: '#ff5252',
backgroundColor: '#ff5252',
yAxisID: 'y-axis-a',
xAxisID: 'x-axis-line',
lineTension: 0.5,
order:1,
},{
type: 'bar',
label: 'Bar graph',
data: diff,
borderColor: colors,
backgroundColor: colors,
borderWidth: 2,
pointRadius: 5,
xAxisID: 'x-axis-bar',
pointBorderWidth: 1,
pointHoverRadius: 7,
pointHoverBorderWidth: 2,
fill: true,
showLabelBackdrop:true,
order:2
},]
};
const config = {
data: data,
options: {
responsive: false,
scales: {
y: {
display:false,
beginAtZero: true,
ticks: {
color: "#ffffff",
font: {
size: 14,
},
},
},
'x-axis-bar':{
ticks:{
autoSkip:false,
stepSize:1.0,
}
},
'x-axis-line':{
display:false
}
},
plugins: {
labels: {
ticks:{
font: {
size: 22
},
color: "#ffffff",
}
},
title: {
display: true,
text: title,
padding: {
top: 10,
bottom: 30,
},
font: {
size: 22,
},
color: "#ffffff"
}
}
}
};
const ctx = document.querySelector(`#chart${index+1}`).getContext('2d');
const myChart = new Chart(ctx, config)

How to set percentage value by default on each bars in horizontal bar chart js

I have used horizontal bar chart from chart.js where i need percentage values to be shown next to each bar at right side? here is the bar sample image.
click here to view sample image of bar chart
Also these are the options i have tried :
xAxes: [
{
ticks: {
min: 0,
max: 100
},
grid: {
offset: false
}
},
],
yAxes: [
{
gridLines: {
display: false,
},
display: "right",
barPercentage: 0.8,
minBarLength: 2,
},
],
Is there any option which can turn the percentage values on at he right side of the horizontal bar chart?
Please click below image to see the expected output
click image expected output
You can make use of the datalabels plugin
Example:
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.3.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
var ctx = document.getElementById('myChart');
Chart.register(ChartDataLabels);
Chart.defaults.set('plugins.datalabels', {
color: '#FE777B'
});
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [ChartDataLabels],
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
data: [12, 19, 3, 5, 2, 3],
label: 'Advisor Closed MTD',
backgroundColor: 'rgb(192,111,94)',
barThickness: 25,
datalabels: {
color: '#FFCE56'
}
}],
},
options: {
indexAxis: 'y',
responsive: false,
plugins: {
datalabels: {
formatter: (val, context) => (`${val}%`),
anchor: 'end',
align: 'end',
labels: {
value: {
color: 'blue'
}
}
}
}
}
});
</script>

ChartJS - Labels getting cutoff using datalabels plugin

I have a simple bar chart and I'm using the datalabels plugin to place labels inside each bar and at the top.
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['One', "Two"],
datasets: [{
data: [40, .5],
backgroundColor: [
'rgba(255, 99, 132)',
'rgba(54, 162, 235)'
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
max: 40
},
}],
xAxes: [{
maxBarThickness: 50
}]
},
plugins: {
datalabels: {
display: true,
anchor: 'end',
align: 'top',
color: 'white',
offset: -30,
font: {
weight: 'bold',
size: 14
}
}
}
}
});
But sometimes, I'll have a value that doesn't allow enough room for the label. See second bar on https://jsfiddle.net/myckxLun/1/.
I want to make sure I have X amount of room for these labels. I've tried minBarLength for the Y-axis - but all this does is force the bar length to be a min pixel value and doesn't adjust the graph (i.e. the bar length is inaccurate).
Ideas on how I can fix this? Thanks!

Chart.js stacked column does not recognize the stack parameter, all in one column

I following the example of Chart.js for a stacked colum graph
http://www.chartjs.org/samples/latest/charts/bar/stacked-group.html
But when I try to replicate for my graph... the stack parameter does not works.
I use the version 2.4.
Here is my code
var color = Chart.helpers.color;
var barChartData = {
labels: [1,2,3,4,5,6,7]<?php // echo ($asse) ?> ,
datasets: [
{
label: '2016',
backgroundColor: color('#FCB441').alpha(0.5).rgbString(),
borderColor: '#FCB441',
borderWidth: 1,
data: [2,4,6,8,10,12,14] ,
stack: 0,
},
{
label: '2017',
backgroundColor: color('#FF0000').alpha(0.5).rgbString(),
borderColor: '#FF0000',
borderWidth: 2,
data: [2,4,6,8,10,12,14] ,
stack: 0,
},
{
label: '3',
backgroundColor: color('#FFFF00').alpha(0.5).rgbString(),
borderColor: '#FFFF00',
borderWidth: 2,
data: [1,2,3,4,5,6,7] ,
stack: 1,
},
]
};
window.onload = function() {
var ctx = document.getElementById('Chart_<?php echo $this->id ?>').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
};
`});
Here is my graph:
My Graph
I still don't get it where's my mistake, it seems like the demo code.
Thanks in advice.
Phil

Chart.js v2 - combined stacked bar chart and 2 unstacked lines

Can Chart.js v2.x generate a combined stacked bar chart with 2 unstacked lines utilizing one y-axis? If so, how?
Below fiddle has 2 y-axis. The descending line, would render better if the right y-axis had a maximum value of 6000 as does the left axis.
jsfiddle example.
Below is the code for reference.
// set default no fill beneath the line
Chart.defaults.global.elements.line.fill = false;
// stacked bar with 2 unstacked lines - nope
var barChartData = {
labels: ['2016', '2017', '2018', '2019'],
datasets: [{
type: 'bar',
label: 'a',
yAxisID: "y-axis-0",
backgroundColor: "rgba(217,83,79,0.75)",
data: [1000, 2000, 4000, 5000]
}, {
type: 'bar',
label: 'b',
yAxisID: "y-axis-0",
backgroundColor: "rgba(92,184,92,0.75)",
data: [500, 600, 700, 800]
}, {
type: 'line',
label: 'c',
yAxisID: "y-axis-0",
backgroundColor: "rgba(51,51,51,0.5)",
data: [1500, 2600, 4700, 5800]
}, {
type: 'line',
label: 'd',
yAxisID: "y-axis-1",
backgroundColor: "rgba(151,187,205,0.5)",
data: [5000, 3000, 1000, 0]
}]
};
var ctx = document.getElementById("chart").getContext("2d");
// allocate and initialize a chart
var ch = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: "Chart.js Bar Chart - Stacked"
},
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true,
position: "left",
id: "y-axis-0",
}, {
stacked: false,
position: "right",
id: "y-axis-1",
}]
}
}
});
Turns out, I just needed a modification or two so that the 2 y-axis use the same scale. See this jsfiddle. Now the chart renders better. The key, in my case, is adding a ticks node and these two properties to both yAxes objects:
ticks: {
beginAtZero: true,
suggestedMax: 5800
}
Naturally, the suggestedMax value would not be hard coded. Further, since the 2 scales are now the same, I hid the right scale with this property setting display: false.
As the fiddle shows, we now have 2 unstacked lines on a stacked bar chart nicely rendered.
Use this as the data for the graph:
var barData = {
labels: ['test1','test2'],
datasets: [
{
label: 'stack1',
backgroundColor: 'yellow',
borderColor: 'white',
borderWidth: 1,
stack: '1',
data: [5,4,3,2,1]
},
{
label: 'stack2',
backgroundColor: 'blue',
borderColor: 'white',
borderWidth: 1,
stack: '2',
data: [1,2,3,4,5]
}
]
};
This is the component to render the data:
<Bar data={barData} options={{scales: { xAxes: [{stacked:true}} }], yAxes:[{stacked:true}}] } }}}} />

Categories

Resources