How to increase line chart width in ng2-charts? - javascript

I am trying to render a line chart using "ng2-charts": "^2.3.0" and "chart.js": "^2.8.0",. Chart is displaying as expected but only problem is that I am not able to increase the line width with borderWidth property.
Code:
import { SingleDataSet, Label, Color } from "ng2-charts";
import { ChartType, ChartOptions } from "chart.js";
public barChartType1: ChartType = "line";
public lineChartOptions: ChartOptions = {
responsive: true,
legend: { display: false },
scales: {
yAxes: [
{
display: false,
ticks: {
beginAtZero: false
},
scaleLabel: {
display: true,
labelString: '',
fontSize: 20,
}
},
]
},
elements: {
point:{
radius: 0,
borderWidth: 50
}
},
};
public lineChartColors: Color[] = [
{
borderColor: '#5081bd',
backgroundColor: 'transparent',
},
];
Template:
<canvas baseChart height="30vh" width="80vw"
[colors]="lineChartColors"
[datasets]="barChartDataSets1[customdata.index]"
[labels]="barChartLabels1[customdata.index]"
[options]="lineChartOptions"
[chartType]="barChartType1"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)">
</canvas>
Inputs:
barChartDataSets1 [{"data":["2.00","2.00","2.00","2.00","2.00","2.00","2.00","2.00"]
barChartLabels1 [" "," "," ","ans1"," "," "," ","ans2"]
Output:
Is there any solution for this and why changing borderWidth property isn't working on it?

This is because you placed the option in the wrong namespace instead of using options.elements.point you need to place it in options.elements.line:
elements: {
point: {
radius: 0,
},
line: {
borderWidth: 8
}
},

Related

How to create a bar and a line in a same graph using chart.js in React?

(Requirement: The bar has to start from the first tick(i.e label "a" below) in x axis whereas the line has to start from third tick(label "c" below)).
I have tried the following way.
import React from "react";
import Chart from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
class Barchart extends React.Component {
//chart= null;
componentDidMount(){
this.configureChart();
}
configureChart = ()=>{
let bardata=[7, 3, 2];
let linedata=[ 0,0,0,75, 55, 80, 65];
// xaxislabel=["a","b","c"]
// xaxislabelline=["d","e","f","g"]
const node=this.node;
new Chart(node,{
plugins: [ChartDataLabels],
type:'',
data:{
datasets:[
{
yAxisID:'A',
label: "Bar Dataset",
data: bardata ,
type: "bar",
backgroundColor: "#DE924B",
order:1
},
{
yAxisID:'B',
label: "Line Dataset 2",
data: linedata,
type: "line",
fill: false,
borderColor: 'rgb(75, 192, 192)',
order:2
},
],
labels:["a","b","c","d","e","f","g"]
},
options:{
scales:{
yAxes:[
{ id:'A',
display:true,
ticks:{
beginAtZero:true
}
},
{ id:'B',
display:true,
ticks:{
beginAtZero:true
}
}
],
xAxes:[
{ id:'C',
display: true,
barThickness: 25,
ticks: {
beginAtZero: true,
}
},
{ id:'D',
display: true,
ticks: {
beginAtZero:true,
min:'c',
}
}
},
]
}
}
})
}
render(){
return(
<div>
<canvas
style={{ width: 650, height: 165 }}
ref={node => (this.node = node)}
/>
</div>
);
}
}
export default Barchart;
Below is the attached result I got.
I am not sure how to have the line graph start from label "c" of the main label(or have single label for both graphs).
Found the solution.
changed
let linedata=[ 0,0,0,75, 55, 80, 65]-->
let linedata=[ null,null,null,75, 55, 80, 65];

Chart.js : How I change the x axes ticks labels alignment in any sizes?

How can I move my labels on my x axes in between another x axes label. Nothing seems to work and I was unable to find anything on the docs. Is there a workaround? I'm using line chart time series.
https://www.chartjs.org/samples/latest/scales/time/financial.html
Currently, with the code I have its generating the figure below:
var cfg = {
elements:{
point: {
radius: 4
}
},
data: {
datasets: [
{
label: 'vsy',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
data: firstData,
type: 'line',
pointRadius: 2,
fill: false,
lineTension: 0,
borderWidth: 2
},
{
label: 'de vsy',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
data: dataMaker(15),
type: 'line',
pointRadius: 2,
fill: false,
lineTension: 0,
borderWidth: 2
}
],
},
options: {
animation: {
duration: 0
},
scales: {
xAxes: [{
type: 'time',
distribution: 'series',
offset: true,
time: {
unit: 'month',
displayFormats: {
month: 'MMM'
}
},
ticks: {
autoSkip: true,
autoSkipPadding: 75,
sampleSize: 100
},
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index',
}
}
};
This is what I have now:
I want the labels on the x-axis to be on center instead of below the y axis grid line.
Thanks to uminder, with his comment it solves the issue but now I have a conflicting tooltip which lie on a same grid. When I hover to april line first point it shows me mar 30 which lies just above it and vice versa.
I fixed it by changing the mode to nearest but why is it activating the another point?
The option you're looking for is offsetGridLines.
If true, grid lines will be shifted to be between labels.
xAxes: [{
...
gridLines: {
offsetGridLines: true
}
In most cases, this produces the expected result. Unfortunately it doesn't work for time axes as documented in Chart.js issue #403. Thanks to Antti Hukkanen, there exists a workaround.
Please have a look at below runnable code snippet to see how it works.
function generateData() {
var unit = 'day';
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomPoint(date, lastClose) {
var open = randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);
var close = randomNumber(open * 0.95, open * 1.05).toFixed(2);
return {
t: date.valueOf(),
y: close
};
}
var date = moment().subtract(1, 'years');
var now = moment();
var data = [];
for (; data.length < 600 && date.isBefore(now); date = date.clone().add(1, unit).startOf(unit)) {
data.push(randomPoint(date, data.length > 0 ? data[data.length - 1].y : 30));
}
return data;
}
var TimeCenterScale = Chart.scaleService.getScaleConstructor('time').extend({
getPixelForTick: function(index) {
var ticks = this.getTicks();
if (index < 0 || index >= ticks.length) {
return null;
}
// Get the pixel value for the current tick.
var px = this.getPixelForOffset(ticks[index].value);
// Get the next tick's pixel value.
var nextPx = this.right;
var nextTick = ticks[index + 1];
if (nextTick) {
nextPx = this.getPixelForOffset(nextTick.value);
}
// Align the labels in the middle of the current and next tick.
return px + (nextPx - px) / 2;
},
});
// Register the scale type
var defaults = Chart.scaleService.getScaleDefaults('time');
Chart.scaleService.registerScaleType('timecenter', TimeCenterScale, defaults);
var cfg = {
data: {
datasets: [{
label: 'CHRT - Chart.js Corporation',
backgroundColor: 'red',
borderColor: 'red',
data: generateData(),
type: 'line',
pointRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2
}]
},
options: {
animation: {
duration: 0
},
scales: {
xAxes: [{
type: 'timecenter',
time: {
unit: 'month',
stepSize: 1,
displayFormats: {
month: 'MMM'
}
},
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index'
}
}
};
var chart = new Chart('chart1', cfg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart1" height="90"></canvas>
For chartJs v3 you can use offset property:
scales: {
x: {
grid: {
offset: true
}
},
...
}

How to only draw the graph and the Xaxis gridlines using chart.js

I am trying to draw a graph, but the left and the bottom corners keep getting this blank margin. How do I get rid of that? I managed to erase them, but at the same time it erases the gridLines for the X axis. I want to keep the Xaxis gridlines.
Notice that I also want that border around the graph. Didn't find a way to draw the border using the chart.js.
The white spaces are very evidient, right on the bottom and on the left, spacing the gray border away. You can see it on the image:
I tried disabling the ticks display.
My chart so far:
var myChart = new Chart(modalChart, {
type: 'bar',
data: {
labels: ['Total enviado', 'Total recebido', 'total aberto', 'total convertido'],
datasets: [{
backgroundColor: my_gradient,
data: [totalEnviado,totalRecebido, totalAberto,totalConvertido]
}]
},
options: {
legendCallback: function(chart){
var text = [];
text.push('<div class = "modal-graph-container">');
text.push('<div class = "modal-graph-inner">');
for (var i=0; i<chart.data.labels.length; i++) {
console.log(chart.data.datasets[i]); // see what's inside the obj.
text.push('<div class = "modal-graph-child">');
text.push('<span style="">' + chart.data.labels[i] + '</span>');
console.log(chart.data.labels[i]);
text.push('</div>');
}
text.push('</div>');
text.push('</div>');
return text.join("");
},
legend: {
display:false
},
scales: {
xAxes:[{
display: true,
categoryPercentage:1.0,
barPercentage:1.0,
ticks: {
beginAtZero: true,
display:false
}
}],
yAxes: [{
ticks: {
beginAtZero:true,
display: false
},
gridLines:{
display:false
}
}]
}
}
});
Notice that I also want that border around the graph. Didn't find a way to draw the border using the chart.js only. This gray border around the graph and the gray borders separating the bars are very important.
You need to set the drawTicks option to false for both the x- and y-axis:
gridLines: {
drawTicks: false
}
Working example:
var modalChart = document.getElementById("chart"),
totalEnviado = 4,
totalRecebido = 3,
totalAberto = 2,
totalConvertido = 1,
my_gradient = "orange";
// --
var myChart = new Chart(modalChart, {
type: 'bar',
data: {
labels: ['Total enviado', 'Total recebido', 'total aberto', 'total convertido'],
datasets: [{
backgroundColor: my_gradient,
data: [totalEnviado, totalRecebido, totalAberto, totalConvertido]
}]
},
options: {
legendCallback: function(chart) {
var text = [];
text.push('<div class = "modal-graph-container">');
text.push('<div class = "modal-graph-inner">');
for (var i = 0; i < chart.data.labels.length; i++) {
console.log(chart.data.datasets[i]); // see what's inside the obj.
text.push('<div class = "modal-graph-child">');
text.push('<span style="">' + chart.data.labels[i] + '</span>');
console.log(chart.data.labels[i]);
text.push('</div>');
}
text.push('</div>');
text.push('</div>');
return text.join("");
},
legend: {
display: false
},
scales: {
xAxes: [{
display: true,
categoryPercentage: 1.0,
barPercentage: 1.0,
ticks: {
beginAtZero: true,
display: false
},
gridLines: {
drawTicks: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
display: false
},
gridLines: {
display: false,
drawTicks: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="border:1px solid #000">
<canvas id="chart"></canvas>
</div>

Add Data Labels onto a bubble chart on chart.js

I have used a Bubble Chart on Chart.js to create sliders to show comparable performance and they currently look a bit like this:
What am I trying to do
I want to add data labels just above / in my 'bubbles' with my values in. Much like the '10' you can see on each bubble here.
What have I done to achieve this
This is not standard Chart.js functionality but I found this post which was discussing a similar issue for bar / line charts.
I've installed the plugin that post suggested but the data label it shows is for the radius of the bubble and I want to it to be the x-axis of the bubble.
I've also tried to use the code from some of the answers on that post, but with absolutely no luck.
My Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<div class="container" >
<h2>Chart.js — Line Chart Demo</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
ctx.height = 1000;
var myChart = new Chart(ctx, {
type: 'bubble',
data: {
datasets: [
{
label: 'Your Data',
data: [
{x: 78.7, y: 0, r: 10, name: "Performance"}
],
backgroundColor: "rgba(153,255,51,0.6)"
},
{
label: 'Average',
data: [
{x: 100.7, y: 0, r: 10, name: "Performance"} // The labe needs to be X. not R.
],
backgroundColor: "rgba(255,0,128,0.6)"
}
]
},
options: {
maintainAspectRatio: false,
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
ticks: {
min: 0,
max: 1,
stepSize: 1,
display: false
},
gridLines: {
display: false,
drawBorder: false
}
}],
xAxes: [{
ticks: {
min: 50, // Controls where axis starts
max: 120 // Controls where axis finishes
},
gridLines: {
display: false,
lineWidth: 3 // Width of bottom line
}
}]
}
}
});
</script>
Thanks in advance
I've managed to find the answer to this question, basically by taking apart the bubble chart example from the chartjs-plugin-datalabels plugin.
Below is a working example. Pay attention to the section in options that says 'plugin'.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<div class="container" >
<h2>Chart.js — Line Chart Demo</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
ctx.height = 1000;
var myChart = new Chart(ctx, {
type: 'bubble',
data: {
datasets: [
{
label: 'Your Data',
data: [
{x: 78.7, y: 0, r: 10, name: "Performance"}
],
backgroundColor: "rgba(153,255,51,0.6)"
},
{
label: 'Average',
data: [
{x: 100.7, y: 0, r: 10, name: "Performance"} // The labe needs to be
],
backgroundColor: "rgba(255,0,128,0.6)"
}
]
},
options: {
plugins: { // Look at this bit
datalabels: {
anchor: function(context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 50 ? 'end' : 'center';
},
align: function(context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 50 ? 'end' : 'center';
},
color: function(context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 50 ? context.dataset.backgroundColor : 'white';
},
font: {
weight: 'bold'
},
formatter: function(value) {
return Math.round(value.x);
},
offset: 2,
padding: 0
}
},
maintainAspectRatio: false,
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
ticks: {
min: 0,
max: 1,
stepSize: 1,
display: false
},
gridLines: {
display: false,
drawBorder: false
}
}],
xAxes: [{
ticks: {
min: 50, // Controls where axis starts
max: 120 // Controls where axis finishes
},
gridLines: {
display: false,
lineWidth: 3 // Width of bottom line
}
}]
}
}
});
</script>
If all you want to do is changing the label, there is an easier solution. From the docs of chartjs-plugin-datalabels:
Data values are converted to string ('' + value). If value is an object, the following rules apply first:
value = value.label if defined and not null
else value = value.r if defined and not null
else value = 'key[0]: value[key[0]], key[1]: value[key[1]], ...'
Therefore, it is sufficient to specify a label in your data points:
data: [{ x: 78.7, y: 0, r: 10, name: "Performance", label: `${Math.round(x)}` }],

ng2-charts Doughnut Chart How to make labels visible every time along with the corresponding count than just showing in tooltip

Is there any option available in ng2-chart(http://www.chartjs.org/docs/latest/) - Doughnut chart, to make the labels visible every time in the graph than just showing them in the tooltip?
Component:
public mobileChartOptions: any = {
responsive: true,
legend: {
display: true,
position: 'bottom',
labels: {
padding: 10
}
}
};
public mobileOptions = Object.assign({
elements: {
arc: {
borderWidth: 0
}
}
}, this.mobileChartOptions);
public mobileUsersData: {
colors: [{
backgroundColor: ["#3FB7D0", "#6C71CC", "#ffeb3b", "#4caf50", "#2196f"]
}],
options: this.mobileOptions,
chartType: 'doughnut',
labels: [],
data: [],
loaded: false,
dataAvailable: false
};
Html:
<canvas height=" " baseChart class="chart"
[data]="mobileUsersData.data"
[labels]="mobileUsersData.labels"
[options]="mobileOptions"
[colors]="mobileUsersData.colors"
[chartType]="mobileUsersData.chartType"
(chartHover)="chartHovered($event)">
</canvas>

Categories