Chartjs scales.xAxis: Property 'title' does not exist on type '_DeepPartialObject - chart.js

I have upgraded from chartjs v2.8.0 to 4.2.1, and I am trying to set the legend title in a line chart, however I am getting this vscode error...
However if I look at the object, title certainly seems to be there...
Any ideas why I am getting this type error, or alternatively how to set the legend text (dynamically)?
[UPDATE1]
As extra information, here is how I set up my chart (in an Angular component)
/**
* Create the chart and empty data object
*/
private createChart(): void {
if (this.chart !== undefined) {
return;
}
Chart.register(LineController, PointElement, Tooltip, Legend, TimeScale, LinearScale, CategoryScale, LinearScale, LineElement);
this.chartData = {
datasets: [{
fill: false, // shading under the line
data: []
}]
};
const options: ChartOptions = {
plugins: {
legend: {
display: false,
labels: {
padding: 10
}
}
},
elements: {
line: {
borderColor: this.lineColour // line colour
}
},
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
ticks: {
source: 'auto',
maxRotation: 60,
minRotation: 60,
autoSkip: true,
},
grid: {
color: this.gridLinesColor
},
//label: { labelString: '', display: true },
type: 'time',
display: true,
position: 'bottom',
time: {
unit: 'minute',
displayFormats: {
minute: this.runtimeStatusService.getCacheTimePattern()
}
}
},
y:
{
min: 0,
grid: {
color: this.gridLinesColor,
},
}
}
};
this.chart = new Chart(this.chartRef.nativeElement, {
type: 'line',
data: this.chartData,
options
});
}
And this is how I use to be able to set the x Axis legend text (in v2)
this.chart.config.options.scales.xAxes[0].scaleLabel.labelString = legendText;
And it use to show up like this....
So I just want to do the same in v4

I found I could do what I was after by now adding a chart title.
First I add title to the register..
Chart.register(LineController, PointElement, Tooltip, Legend, Title /* <-- add this **/, TimeScale, LinearScale, CategoryScale, LinearScale, LineElement);
Next I add the title to the plugings...
const options: ChartOptions = {
plugins: {
legend: {
display: false, <---- HIDE THIS
position: 'bottom',
labels: {
padding: 10,
}
},
title: {
display: true, <---- SHOW THIS
position: 'bottom',
text: ''
},
},
And now I can set the title at runtime...
this.chart.config.options.plugins.title.text = 'hello';
In my case, this is all I am after...

Related

GBP currency conversion of Apex Charts data labels

I'm learning to work with Apexcharts and need to show the labels (Y axis labels an data labels) as currency (GBP) but can't seem to find the right approach. I have looked at the locale code, but really not sure how to integrate this into my chart.
I'm trying to ensure that 1000 become 1,000 etc.
Below is the chart code
<script>
var options = {
series: [
{
name: "Price in £s",
data: [1000, 2000, 2500, 3000, 4800, 6000]
}
],
chart: {
height: 350,
type: 'bar',
id: 'areachart-2',
dropShadow: {
enabled: true,
color: '#000',
top: 18,
left: 7,
blur: 10,
opacity: 0.2
},
toolbar: {
show: false
}
},
colors: ['#f6564d', '#545454'],
dataLabels: {
enabled: false,
textAnchor: 'middle',
formatter: function(val, index) {
return val.toFixed(0);
}
},
stroke: {
curve: 'straight'
},
title: {
text: '',
align: 'left'
},
grid: {
borderColor: '#f1f1f1',
row: {
colors: ['#fff', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
markers: {
size: 100
},
xaxis: {
categories: ['01/05/22','01/06/22','01/07/22','01/08/22','01/09/22','01/10/22'],
title: {
text: 'Month'
}
},
yaxis: {
min:00,
title: {
text: 'Price in GBP',
},
},
legend: {
position: 'top',
horizontalAlign: 'right',
floating: true,
offsetY: 100,
offsetX: 100
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
</script>
In yaxis add labels formatter
labels:{
formatter: (value) => {
return `${numberWithCommas(value)} GBP`;
},
},
And use this regex to add commas
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
Axes labels formatting can be controlled by yaxis.labels.formatter and xaxis.labels.formatter.
yaxis: {
labels: {
formatter: function (value) {
return value + "$";
}
},
},
xaxis: {
labels: {
formatter: function (value) {
return value;
}
}
}

Why does x axis not increment 'monthly' chart.js. Also, XAxis not taking title

https://water.sas.usace.army.mil/chart.htm
https://water.sas.usace.army.mil/chart.png
See the Code Above, (View Source)
The code builds a time-series chart.
The scales section has unit set to month, however chart does not display with monthly increment on x axis.
Also Y axis will not display title.
The main problem is that config is not properly formatted, options.plugins is not closed by a }, hence the entire scales section is not considered by Chart.js.
Further, you should also define a time.parser to let the date adapter know how to parse the provided date strings.
Be careful to choose the correct date-fns formats for time.parser as well as for time.displayFormats.
Therefore, if you define config as follows, it should work.
const config = {
type: 'line',
data: data,
options: {
responsive: true,
plugins: {
legend: {
display: true,
position: 'bottom'
},
title: {
display: true,
text: "HARTWELL PROJECT",
font: {
size: 20
}
},
},
scales: {
x: {
type: 'time',
time: {
parser: 'MM/dd/yyyy',
unit: 'month',
displayFormats: {
month: 'MMM yyyy'
}
},
title: {
display: true,
text: 'Date'
}
},
y: {
title: {
position: 'left',
display: true,
text: 'Elevation (FT-MSL)'
}
}
},
chartAreaBorder: {
borderColor: 'black',
borderWidth: 10,
//borderDash: [5, 5],
borderDashOffset: 5
},
imgPlugin: {}
},
plugins: [chartAreaBorder, imgPlugin, GradientBgPlugin]
};

Add labels to bar chart: chartjs

I am creating bar charts using chartjs 3.5.1, and I am new to chartjs. I want to add value labels to each bar in my bar chart.
I have reviewed some relevant answers, but they are either too old or too complicated to achieve.
Below is the intended outcome, note that the non-hand-written part is what I have achieved.
The code is below:
let chart2 = new Chart('chart2', {
type: 'bar',
data: {
labels: ["a", "b", "c", "d"],
datasets: [{
data: [500, 400, 300, 200],
}]
},
options: {
indexAxis: 'y',
plugins: {
title: {
display: true,
text: "Graph"
},
legend: {
display: false,
}
},
scales: {
y: {
grid: {
display: false
},
},
x: {
grid: {
display: false
}
}
}
},
});
Really appreciate your help!
You can use the chartjs-plugin-datalabels library.
First you'll have to register the plugin, then you can define the desired options inside options.plugins.datalabels.
Please take a look at your amended code and see how it works.
Chart.register(ChartDataLabels);
new Chart('chart2', {
type: 'bar',
data: {
labels: ["a", "b", "c", "d"],
datasets: [{
data: [500, 400, 300, 200],
}]
},
options: {
indexAxis: 'y',
layout: {
padding: {
right: 60
}
},
plugins: {
title: {
display: true,
text: "Graph"
},
legend: {
display: false,
},
datalabels: {
color: 'blue',
anchor: 'end',
align: 'right',
labels: {
title: {
font: {
weight: 'bold'
}
}
}
}
},
scales: {
y: {
grid: {
display: false
},
},
x: {
grid: {
display: false
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="chart2" height="100"></canvas>

rotating y-axis to top and x-axis to left within chart.js

I have a chart that's currently displaying like:
But I'd like to rotate it to look more like this:
(not changing the "your rating") orientation.
It should be relatively straightforward to put the x-axis on the left and the y-axis on the top, but I'm struggling.
Here is the relevant code:
var ctx = document.getElementById('canvas').getContext('2d');
window.myHorizontalBar = new Chart(ctx, {
type:'line', // 'horizontalBar',
data: horizontalBarChartData,
options: {
annotation: {
annotations: [{
type: 'line',
mode: 'vertical',
scaleID: 'y-axis-0',
value: 20,
label: {
content: 'Your Rating ',
enabled: true
}
}]
},
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
},
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each horizontal bar to be 2px wide
responsive: true,
legend: {
display: false
},
title: {
display: false,
text: 'text4'
}
}
});
}

How can I change the color of certain lines in chartjs / vue-chartjs?

I notice that a default bar chart always has a darker zero line. I also notice the horizontal line at -1.0 is also darker. I want those colors to be the same as the grid. How do I do that?
A bare-bones example is shown here:
https://jsfiddle.net/Lnv3cmz0/1/
Vue.component('chart', {
template:`
<canvas></canvas>
`,
props:['type'],
mounted(){
this._chart = new Chart(this.$el, {
type:this.type,
data:[],
})
},
})
//App setup
new Vue({
el:'#vue',
})
Update:
The zeroLine option no longer seems to be available. I am using the latest/greatest Chart (v4.2.0) and no longer have this issue. Below is a sample of what I'm doing
const ctx = document.getElementById('chart') as HTMLCanvasElement;
chart.value = new Chart(ctx, {
type: 'bar',
data: {
datasets: [],
},
options: {
onClick: (evt) => handleOnClick(evt),
interaction: {
mode: 'nearest',
},
plugins: {
legend: {
labels: {
generateLabels(chart) { // other code here }}
}
},
title: {
display: true,
text: 'My Super cool Chart',
},
},
scales: {
x: {
grid: {
color: () => myBackgroundColor,
},
beginAtZero: false,
ticks: {
callback: (value) => doSomethingOnCallaback(value),
// fontColor: myBackgroundColor,
},
type: 'linear',
},
y: {
grid: {
color: () => myBackgroundColor,
},
max: myStart,
min: myEnd,
beginAtZero: false,
ticks: {
callback: (value) => `Tick ${value}`,
stepSize: 15.0,
},
},
},
},
});
The answer is zeroLineColor in the GridLines
https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration