Chartjs: Make some ticks (Sunday, Saturday) red - javascript

I try to make the ticks the red. but it not working. When labels has not the labels - Sa/Su it work. All labels - grey, but when i have Su or Sa labels make just black color
ticks: {
fontSize: 9,
fontColor: curLabels.map((item) => {
if(item === 'Su' || item === 'Sa')
return 'red';
return 'rgba(0, 0, 0, 0.4)';
}),
maxRotation: 0,
},
Edited:
<div style={{height: '100%'}} className='position-relative'>
<Line
key='lineChart17'
data={dataForChart}
options={lineOptions}
style={{height: '90px', padding: '5px', width: '100%'}}
redraw
/>
</div>
Options for chart. I get error - ticks has not properties major. In console it just the string - Mo/Th/Fr/We/Su ...:
const lineOptions = {
animation: {
duration: 0
},
layout:{
padding:{
left: 0,
right: 0,
top: 5,
bottom: 0
}
},
maintainAspectRatio: false,
scales: {
xAxes: [{
display: true,
gridLines: {
display: true,
tickMarkLength: 1,
},
ticks: {
fontSize: 9,
fontColor: 'rgba(0, 0, 0, 0.4)',
maxRotation: 0,
major: {
enabled: true,
fontStyle: 'bold',
fontColor: 'red'
},
},
afterBuildTicks: (scale, ticks) => {
ticks.forEach(t => {
t.major = (t === 'Su');
});
return ticks;
},
}],
yAxes: [{
display: false,
gridLines: {
display: false,
tickMarkLength: 1,
},
}],
},
};

According to Chart.js documentation, the option ticks.fontColor doesn't accept an array but a simple string.
You can however define the style of your weekend ticks through the ticks.major configuration as follows.
ticks: {
major: {
enabled: true,
fontStyle: 'bold',
fontColor: 'red'
}
},
Further you need to mark the desired ticks as major through the afterBuildTicks callback.
afterBuildTicks: (scale, ticks) => {
ticks.forEach(t => {
const day = new Date(t.value).getDay();
t.major = (day == 0 || day == 6);
});
return ticks;
}
Please take a look at the runnable code snippet below.
const dates = [];
let day = new Date('2020-01-01');
for (let i = 0; i < 20; i++) {
dates.push(new Date(day.getFullYear(), day.getMonth(), day.getDate()));
day.setDate(day.getDate() + 1);
};
function generateData() {
return dates.map(d => ({ x: d, y: Math.floor(Math.random() * 10) + 1 }));
};
new Chart('myChart', {
type: 'bar',
data: {
datasets: [{
label: 'My Dataset',
data: generateData(),
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 132)',
borderWidth: 1
}
]
},
options: {
scales: {
xAxes: [{
offset: true,
type: 'time',
time: {
unit: 'day',
displayFormats: {
day: 'dd D MMM',
month: 'dd D MMM'
},
tooltipFormat: 'dd D MMM'
},
ticks: {
major: {
enabled: true,
fontStyle: 'bold',
fontColor: 'red'
}
},
afterBuildTicks: (scale, ticks) => {
ticks.forEach(t => {
const day = new Date(t.value).getDay();
t.major = (day == 0 || day == 6);
});
return ticks;
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 2
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.0/Chart.bundle.min.js"></script>
<canvas id="myChart" height="100"></canvas>

Related

How can I change background color of a specific area in my chart's grid using Chart.js and Annotation?

I'm having some trouble trying to change the backgroundColor of a specific chart area between two yAxis ticks.This is what I have so far:
And this is what I wanted:
I've seen some similar posts about that and people recommend using Annotation to do this. I tried using it on my chart and it didn't work. This is my first time building a chart with chart.js so I'm still learning. Here's my code:
var profileChart = new Chart(ctx1, {
type: "line",
data: {
labels: ["", "D", "I", "S", "C", ""],
datasets:[{
data: [],
borderWidth: 1,
pointBackgroundColor: "black",
backgroundColor: "black",
borderColor: "black",
fill: false,
lineTension: 0,
yAxisID: 'first-y-axis'
},
{
yAxisID: 'third-y-axis'
}],
},
options: {
title: {
display: true,
text: 'Gráfico do Perfil DISC',
fontSize: 20,
},
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '15px',
labelString: 'Intensity'
},
ticks: {
max: 28,
min: 1,
stepSize: 1
}
},
{
id: 'second-y-axis',
type: 'linear',
position: 'left',
gridLines: {
drawOnChartArea: true
},
ticks: {
display: false,
min: 1,
max: 8,
stepSize: 1
}
},
{
id: 'third-y-axis',
position: 'right',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '10px',
labelString: 'Segment'
},
ticks: {
max: 7.5,
min: 0.5,
stepSize: 1
},
afterTickToLabelConversion: function(scaleInstance) {
scaleInstance.ticks[0] = null;
scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
scaleInstance.ticksAsNumbers[0] = null;
scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
},
}]
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
},
annotation: {
drawTime: "afterDraw",
annotations: [{
id: 'box1',
type: 'box',
yScaleID: 'second-y-axis',
yMin: 12.5,
yMax: 16.5,
backgroundColor: 'grey',
}]
}
});
You can draw the rectangle directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.
In your amended code below, I use the beforeDraw hook to draw the rectangle through CanvasRenderingContext2D.fillRect().
var profileChart = new Chart('canvas', {
type: "line",
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['first-y-axis'];
ctx.save();
ctx.fillStyle = 'lightgray';
ctx.beginPath();
var yTop = yAxis.getPixelForValue(16.5);
var yBottom = yAxis.getPixelForValue(12.5);
ctx.fillRect(xAxis.left, yTop, xAxis.right - xAxis.left, yBottom - yTop);
ctx.stroke();
ctx.restore();
}
}],
data: {
labels: ["", "D", "I", "S", "C", ""],
datasets: [{
data: [,25.5, 8, 7.5, 11],
borderWidth: 1,
pointBackgroundColor: "black",
backgroundColor: "black",
borderColor: "black",
fill: false,
lineTension: 0,
yAxisID: 'first-y-axis'
},
{
yAxisID: 'third-y-axis'
}
],
},
options: {
title: {
display: true,
text: 'Gráfico do Perfil DISC',
fontSize: 20,
},
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '15px',
labelString: 'Intensity'
},
ticks: {
max: 28,
min: 1,
stepSize: 1
}
},
{
id: 'second-y-axis',
type: 'linear',
position: 'left',
gridLines: {
drawOnChartArea: true
},
ticks: {
display: false,
min: 1,
max: 8,
stepSize: 1
}
},
{
id: 'third-y-axis',
position: 'right',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '10px',
labelString: 'Segment'
},
ticks: {
max: 7.5,
min: 0.5,
stepSize: 1
},
afterTickToLabelConversion: function(scaleInstance) {
scaleInstance.ticks[0] = null;
scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
scaleInstance.ticksAsNumbers[0] = null;
scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
},
}
]
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="canvas" height="200">

How to reduce number of multiple gridlines in stack bar graph chart.js

I am working on chart.js for implementing stack bar graph. That graph has few issues like
Not showing tick size vertically at left
Showing unwanted horizontal gridlines
Displaying horizontal thick line on top instead of bottom
This is my code
public stackbar()
{
Chart.defaults.global.datasets.bar.barPercentage = 0.5;
Chart.defaults.global.datasets.bar.categoryPercentage = 0.5;
var colors = ['#299DFF','#80FFFF','#F8362B',];
var chBar = document.getElementById("mychart");
var chartData = {
labels: ["Product"],
datasets: [{
label: 'P2',
data: [29566],
backgroundColor: colors[0]
},
{
label: 'P3',
data: [O2],
backgroundColor: colors[1]
},
{
label: 'P4',
data: [3],
backgroundColor: colors[2]
}
]
};
if (chBar) {
new Chart(chBar, {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes: [{
gridLines: {
display:false
},
//barPercentage: 0.5,
//categoryPercentage: 0.5
barPercentage: 0.5,
categoryPercentage: 0.5
}
],
yAxes: [{
gridLines: {
display:true
},
type: 'logarithmic',
ticks: {
beginAtZero: true,
userCallback: (value, index) => {
const remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value))));
if (remain == 1 || remain == 2 || remain == 5 || index == 0) {
return value.toLocaleString();
}
return '';
},
suggestedMax: 80,
padding: 25
}
}]
},
legend: {
display: true,
maxWidth: 100,
padding:30,
fullWidth:true,
position: 'bottom',
lineHeight: 12,
justifyContent: 'space-between',
labels: {
fontSize: 10,
usePointStyle: true
}
},
}
});
}
This is the screenshot
How can I fix these issues?
The horizontal grid lines can be removed through the following configuration in the chart options:
yAxes: [{
gridLines: {
display: false
},
I changed this in your code and removed a few unnecessary definitions and it looks just fine to me as you can see in the following runnable code.
var colors = ['#299DFF', '#80FFFF', '#F8362B'];
var chartData = {
labels: ["Product"],
datasets: [{
label: 'P2',
data: [29566],
backgroundColor: colors[0]
},
{
label: 'P3',
data: [2],
backgroundColor: colors[1]
},
{
label: 'P4',
data: [3],
backgroundColor: colors[2]
}
]
};
new Chart('myChart', {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes: [{
barPercentage: 0.5,
categoryPercentage: 0.5
}
],
yAxes: [{
gridLines: {
display: false
},
type: 'logarithmic',
ticks: {
beginAtZero: true,
userCallback: (value, index) => {
const remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value))));
if (remain == 1 || remain == 2 || remain == 5 || index == 0) {
return value.toLocaleString();
}
return '';
}
}
}]
},
legend: {
display: true,
maxWidth: 100,
padding: 30,
fullWidth: true,
position: 'bottom',
lineHeight: 12,
justifyContent: 'space-between',
labels: {
fontSize: 10,
usePointStyle: true
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<canvas id="myChart" height="150"></canvas>

Line chart doesn't work with type time chart.js

I use chart.js with React and I can't figure out why the line chart doesn't work with type: 'time', maybe I could be missing something:
Chart.js CodeSandbox
import React from "react";
import { Line } from "react-chartjs-2";
const startDate = new Date(2020, 4, 20);
const json = '{"responses":[{"count":"73","rows":[{"values":["1"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["1"]},{"values":["6"]},{"values":["7"]},{"values":["5"]},{"values":["8"]},{"values":["9"]},{"values":["2"]},{"values":["1"]},{"values":["1"]},{"values":["1"]},{"values":["6"]},{"values":["3"]},{"values":["0"]},{"values":["20"]},{"values":["9"]},{"values":["3"]},{"values":["2"]},{"values":["1"]},{"values":["13"]},{"values":["3"]},{"values":["13"]},{"values":["13"]},{"values":["7"]},{"values":["12"]},{"values":["0"]}]}]}';
const values = JSON.parse(json).responses[0].rows.map(row => row.values[0]);
const options = {
legend: {
display: false
},
hover: {
mode: "index",
intersect: false,
animationDuration: 0
},
scales: {
yAxes: [{ position: "right" }],
xAxes: [
{
gridLines: { display: false },
type: "time",
time: {
parser: "MMM D",
unit: "day",
unitStepSize: 5,
displayFormats: {
day: "MMM D"
}
},
ticks: {
min: startDate, //May 20
max: new Date()
}
}
]
},
tooltips: {
mode: "x-axis"
}
};
const data = {
datasets: [
{
label: "data",
fill: false,
data: values,
backgroundColor: "pink",
borderWidth: 2,
lineTension: 0,
borderColor: "pink",
hoverBorderWidth: 2,
pointBorderColor: "rgba(0, 0, 0, 0)",
pointBackgroundColor: "rgba(0, 0, 0, 0)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "pink",
showLine: true
}
]
};
const LineChart = () => {
return (
<div style={{ maxWidth: 1024, margin: "32px auto" }}>
<Line data={data} options={options} />
</div>
);
};
export default LineChart;
You should generate specific dataset like this:
const values = JSON.parse(json).responses[0].rows.map((row, index) => {
let date = new Date(2020, 4, 20);
date.setDate(startDate.getDate() + index)
return {
y: row.values[0],
x: date
};
});
example

Show point values in Radar Chart using chart.js

How can I show the values in the chart using chart.js?
UPDATE: I am using the options below but I couldn't find any answer.
options: {
scale: {
angleLines: {
lineWidth: 0.5,
color: 'rgba(128, 128, 128, 0.2)'
},
pointLabels: {
fontSize: 14,
fontStyle: '300',
fontColor: 'rgba(204, 204, 204, 1)',
fontFamily: "'Lato', sans-serif"
},
ticks: {
beginAtZero: true,
maxTicksLimit: 4,
min: 0,
max: 4,
display: false
}
}
}
Sample pen https://codepen.io/melvik/pen/ZEGaexy
expected result
Thanks in advance
chartjs-plugin-datalabels & chart.js radar.
datalabels Datalabels Formatter
https://chartjs-plugin-datalabels.netlify.com/guide/formatting.html#data-transformation
1/2. Basic example - return "hello world"
2/2. "practical example" - return value:
formatter: function(value, context) {
return context.chart.data.labels[context.value];
}
tooltip: false
Set tooltip to false (We use a visible value instead)
tooltips: false,
Basic snippet example:
// Change default options for ALL charts
Chart.helpers.merge(Chart.defaults.global.plugins.datalabels, {
opacity: 1,
textAlign: 'left',
color: 'white',
borderColor: '#11469e',
borderWidth: 2,
borderRadius: 100,
font: {
weight: 'bold',
size: 12,
lineHeight: 1 /* align v center */
},
padding: {
top: 5
},
/* hover styling */
backgroundColor: function(context) {
return context.hovered ? context.dataset.borderColor : 'white';
},
color: function(context) {
return context.hovered ? 'white' : context.dataset.borderColor;
},
listeners: {
enter: function(context) {
context.hovered = true;
return true;
},
leave: function(context) {
context.hovered = false;
return true;
}
}
});
var data = {
labels: ["Ball Skills", "Shooting", "Physical", "Defence", "Passing"],
datasets: [{
label: "De maria",
backgroundColor: "rgba(38,120,255,0.2)",
borderColor: "rgba(38,120,255, 1)",
data: [90, 86, 76, 65, 82]
}]
};
var options = {
responsive: true,
tooltips: false,
title: {
text: 'chartjs-plugin-datalabels - basic example',
display: true,
position: `bottom`,
},
plugins: {
/* ######### https://chartjs-plugin-datalabels.netlify.com/ #########*/
datalabels: {
/* formatter */
formatter: function(value, context) {
return context.chart.data.labels[context.value];
}
}
},
/* scale: https://www.chartjs.org/docs/latest/axes/radial/linear.html#axis-range-settings */
scale: {
angleLines: {
display: true
},
pointLabels:{
/* https://www.chartjs.org/docs/latest/axes/radial/linear.html#point-label-options */
fontSize: 15,
fontColor: 'black',
fontStyle: 'bold',
callback: function(value, index, values) {
return value;
}
},
ticks: {
/* https://www.chartjs.org/docs/latest/axes/styling.html#tick-configuration */
/* suggestedMax and suggestedMin settings only change the data values that are used to scale the axis */
suggestedMin: 0,
suggestedMax: 100,
stepSize: 25, /* 25 - 50 - 75 - 100 */
maxTicksLimit: 11, /* Or use maximum number of ticks and gridlines to show */
display: false, // remove label text only,
}
},
legend: {
labels: {
padding: 10,
fontSize: 14,
lineHeight: 30,
},
},
};
var myChart = new Chart(document.getElementById("chart"), {
type: 'radar',
data: data,
options: options
});
<canvas id="chart" width="500" height="350"></canvas>
<br>
<br>
chartjs-plugin-datalabels
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0/dist/chartjs-plugin-datalabels.min.js"></script>
codepen: https://codepen.io/ezra_siton/pen/bGdYaLd
Ok I found my answer after spending another +2 hours research by using this package
chartjs-plugin-datalabels

How to display value after the bar using chart.js

My chart.js
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages','HTTP Pages'],
datasets: [{
data: [ {{ $array_https_http[0] }}, {{ $array_https_http[1] }}],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel ;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize:100
}
}],
}
}
});
My tooltips code
Chart.Tooltip.positioners.custom = function(elements, position) {
if (!elements.length)
return false;
var em = elements[0]._model;
return {
x: em.x-((em.x-em.base)/2),
y: em.y+em.height/4
}
}
My output
My expected output
Is there anyone can help me how to put those value after the bar like the second picture. I just want to display the value to know even its zero. My custom tooltips was to show a different hover rather than default. All your help are appreciated and thank you in advance.
You can use the chartjs.datalabel plugin for achieving the need. I have created a fiddle for you -> http://jsfiddle.net/Labkrpf4/
Hope it helps!
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages', 'HTTP Pages'],
datasets: [{
data: [0, 430],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize: 100
}
}],
},
plugins: {
datalabels: {
align: 'end',
anchor: 'end',
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderRadius: 4,
color: 'white',
formatter: Math.round
}
}
}
});

Categories

Resources