score:1
you can make use of the plugin core api. it offers different hooks that may be used for executing custom code. in below code snippet, i use the afterdraw
hook to draw text at a position computed from the chart.scales
.
plugins: [{
afterdraw: chart => {
let ctx = chart.chart.ctx;
let xaxis = chart.scales['x-axis-0'];
let yaxis = chart.scales['y-axis-0'];
let maxvalue = math.max(...chart.data.datasets[0].data);
let minvalue = math.min(...chart.data.datasets[0].data);
ctx.save();
ctx.textalign = 'center';
ctx.font = '12px arial';
ctx.fillstyle = 'white';
ctx.textalign = 'left';
ctx.filltext('dagens hã¸jeste temperatur = ' + maxvalue + 'â°c', xaxis.left + 5, yaxis.top + 5);
ctx.filltext('dagens laveste temperatur = ' + minvalue + 'â°c', xaxis.left + 5, yaxis.top + 18);
ctx.restore();
}
}],
in case you want to draw the text slightly above the top most grid line, you would need to define some extra padding at the top of the chart.
layout: {
padding: {
top: 20
}
},
please take a look at your amended code and see how it works with static data.
const now = new date().gettime();
const times = new array(10).fill().map((v, i) => now - i * 600000).reverse();
var charttempdata = {
labels: times,
datasets: [{
label: 'temperatur',
pointradius: 3,
backgroundcolor: 'rgba(26, 137, 245, 0.2)',
bordercolor: 'rgba(26, 137, 245, 1)',
hoverbackgroundcolor: 'rgba(255, 255, 255, 0)',
hoverbordercolor: 'rgba(255, 255, 255, 0)',
pointbackgroundcolor: 'rgba(12, 68, 122,1)',
pointhoverbordercolor: "rgba(255, 255, 255, 0.8)",
data: [22, 23, 23, 23, 22, 20, 22, 22, 23, 25],
datalabels: {
align: function(context) {
return context.active ? 'left' : 'left';
}
}
}]
};
var linetempgraph = new chart('tempgraphcanvas', {
type: 'line',
plugins: [{
afterdraw: chart => {
let ctx = chart.chart.ctx;
let xaxis = chart.scales['x-axis-0'];
let yaxis = chart.scales['y-axis-0'];
let maxvalue = math.max(...chart.data.datasets[0].data);
let minvalue = math.min(...chart.data.datasets[0].data);
ctx.save();
ctx.textalign = 'center';
ctx.font = '12px arial';
ctx.fillstyle = 'white';
ctx.textalign = 'left';
ctx.filltext('dagens hã¸jeste temperatur = ' + maxvalue + 'â°c', xaxis.left + 5, yaxis.top + 5);
ctx.filltext('dagens laveste temperatur = ' + minvalue + 'â°c', xaxis.left + 5, yaxis.top + 18);
ctx.restore();
}
}],
data: charttempdata,
options: {
maintainaspectratio: false,
tooltips: {
enabled: false,
},
legend: {
display: false,
},
scales: {
xaxes: [{
type: 'time',
time: {
unit: 'minute',
displayformats: {
hour: 'hh:mm'
},
tooltipformat: 'hh:mm',
},
gridlines: {
color: '#999999',
linewidth: 1
},
ticks: {
fontcolor: "#fff",
}
}],
yaxes: [{
type: 'linear',
position: 'left',
gridlines: {
color: '#999999',
linewidth: 1
},
ticks: {
fontcolor: "rgba(255, 255, 255, 1)",
stepsize: 1
}
}]
},
}
});
body {
background-color: #242e42;
color: white;
}
<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.4/chart.js"></script>
<canvas id="tempgraphcanvas"></canvas>
score:0
this is the final look of things now. i'm pleased. might do a few edits, but overall this is what i wanted to achieve.
$(document).ready(function() {
showtempgraph();
});
function handletemperaturedata(data) {
var temptime = [];
var temp = [];
for (var i in data) {
temptime.push(data[i].timestamp);
temp.push(data[i].temperature);
}
var tempmin = math.min(...temp);
var tempmax = math.max(...temp);
var charttempdata = {
labels: temptime,
datasets: [{
label: 'luftfugtighed',
pointradius: 3,
backgroundcolor: 'rgba(26, 137, 245, 0.2)',
bordercolor: 'rgba(26, 137, 245, 1)',
hoverbackgroundcolor: 'rgba(255, 255, 255, 0)',
hoverbordercolor: 'rgba(255, 255, 255, 0)',
pointbackgroundcolor: 'rgba(12, 68, 122,1)',
pointhoverbordercolor: "rgba(255, 255, 255, 0.8)",
data: temp,
datalabels: {
align: function(context) {
return context.active ? 'left' : 'left';
}
}
}]
};
var graphtemptarget = $("#tempgraphcanvas");
chart.defaults.global.defaultfontfamily = "roboto";
var linetempgraph = new chart(graphtemptarget, {
type: 'line',
plugins: [{
afterdraw: chart => {
let ctx = chart.chart.ctx;
let xaxis = chart.scales['x-axis-0'];
let yaxis = chart.scales['y-axis-0'];
let maxvalue = math.max(...chart.data.datasets[0].data);
let minvalue = math.min(...chart.data.datasets[0].data);
ctx.save();
ctx.textalign = 'center';
ctx.font = '14px roboto';
ctx.fillstyle = 'white';
ctx.textalign = 'left';
ctx.filltext('dagens max. temperatur = ', xaxis.left + 5, yaxis.top + 15);
ctx.filltext('dagens min. temperatur = ', xaxis.left + 5, yaxis.top + 40);
ctx.filltext(maxvalue + 'â°c', xaxis.left + 200, yaxis.top + 15);
ctx.filltext(minvalue + 'â°c', xaxis.left + 200, yaxis.top + 40);
ctx.restore();
}
}],
data: charttempdata,
options: {
plugins: {
datalabels: {
backgroundcolor: null,
bordercolor: null,
borderradius: function(context) {
return context.active ? 0 : 0;
},
borderwidth: 1,
color: 'rgba(255, 255, 255, 1)',
font: {
size: 18,
color: 'rgba(255, 255, 255, 1)'
},
formatter: function(value, context) {
value = math.round(value * 100) / 100;
if (context.dataindex === context.dataset.data.length - 1) {
return value + 'â°c';
} else {
return context.active ?
value + 'â°c' :
''
}
},
offset: 8,
padding: 0,
textalign: 'center'
}
},
maintainaspectratio: false,
tooltips: {
enabled: false,
},
legend: {
display: false,
},
responsive: true,
scales: {
xaxes: [{
type: 'time',
time: {
displayformats: {
hour: 'hh:mm'
},
tooltipformat: 'hh:mm',
},
unit: 'day',
gridlines: {
color: 'rgba(153, 153, 153, 1)',
linewidth: 1
},
ticks: {
fontcolor: 'rgba(255, 255, 255, 1)',
}
}],
yaxes: [{
type: 'linear',
position: 'left',
gridlines: {
color: 'rgba(153, 153, 153, 1)',
linewidth: 1
},
ticks: {
fontcolor: "rgba(255, 255, 255, 1)",
}
}, {
type: 'linear',
position: 'right',
weight: 50,
gridlines: {
drawonchartarea: false,
},
ticks: {
display: false
},
scalelabel: {
display: true,
labelstring: 'â°c',
fontcolor: "rgba(255, 255, 255, 1)",
fontsize: 14,
fontstyle: 'bold'
}
}]
},
}
});
}
function showtempgraph() {
$.post("temperaturedata.php", handletemperaturedata);
}
score:1
you could attempt to manually write on the canvas using js
, however the example below modifies your code to
- move the axis to the left
- print the highest and lowest values as the first two ticks
nb. since i don't have access to the data return from the ajax call, i have generated data and called the function. you may use the code below by simply commenting the line with generateandhandletemperaturedata()
in showtempgraph()
and uncommenting $.post("temperaturedata.php", handletemperaturedata);
working demo
$(document).ready(function() {
showtempgraph();
});
function handletemperaturedata(data) {
//console.log(data);
var temptime = [];
var temp = [];
for (var i in data) {
temptime.push(data[i].timestamp);
temp.push(data[i].temperature);
}
var tempmin = math.min(...temp);
var tempmax = math.max(...temp);
var charttempdata = {
labels: temptime,
datasets: [{
label: 'temperatur',
pointradius: 3,
backgroundcolor: 'rgba(26, 137, 245, 0.2)',
bordercolor: 'rgba(26, 137, 245, 1)',
hoverbackgroundcolor: 'rgba(255, 255, 255, 0)',
hoverbordercolor: 'rgba(255, 255, 255, 0)',
pointbackgroundcolor: 'rgba(12, 68, 122,1)',
pointhoverbordercolor: "rgba(255, 255, 255, 0.8)",
data: temp,
datalabels: {
align: function(context) {
return context.active ? 'left' : 'left';
}
}
}]
};
var graphtemptarget = $("#tempgraphcanvas");
var linetempgraph = new chart(graphtemptarget, {
type: 'line',
data: charttempdata,
options: {
plugins: {
datalabels: {
backgroundcolor: null,
bordercolor: null,
borderradius: function(context) {
return context.active ? 0 : 0;
},
borderwidth: 1,
color: 'rgba(255, 255, 255, 1)',
font: {
size: 18,
color: 'rgba(255, 255, 255, 1)'
},
formatter: function(value, context) {
value = math.round(value * 100) / 100;
if (context.dataindex === context.dataset.data.length - 1) {
return value + 'â°c';
} else {
return context.active ?
value + 'â°c' :
''
}
},
offset: 8,
padding: 0,
textalign: 'center'
}
},
maintainaspectratio: false,
tooltips: {
enabled: false,
},
legend: {
display: false,
},
responsive: true,
scales: {
xaxes: [{
type: 'time',
time: {
displayformats: {
hour: 'hh:mm'
},
tooltipformat: 'hh:mm',
},
unit: 'day',
gridlines: {
color: '#999999',
linewidth: 1
},
ticks: {
fontcolor: "#fff",
}
}],
yaxes: [{
type: 'linear',
position: 'left',
gridlines: {
color: '#999999',
linewidth: 1
},
ticks: {
fontcolor: "rgba(255, 255, 255, 1)",
}
}, {
type: 'linear',
position: 'left',
afterupdate: function(scaleinstance) {
//console.dir(scaleinstance);
},
ticks: {
// stepsize: 1 || tempmin - tempmax,
min: tempmin,
max: tempmax,
mirror: true,
padding: -30,
fontcolor: "rgba(255, 255, 255, 1)",
fontsize: 14,
callback: function(value,index) {
// console.log(arguments)
if(index == 0){
return ' dagens hã¸jeste temperatur = ' + tempmax + 'â°c';
}else if(index == 1){
return ' dagens laveste temperatur = ' + tempmin + 'â°c';
}else{
return ""
}
}
},
gridlines: {
drawonchartarea: false,
},
scalelabel: {
display: true,
// labelstring: 'â°c',
fontcolor: "rgba(255, 255, 255, 1)",
fontsize: 14,
fontstyle: 'bold',
//adjust the properties below to change the spacing between the lines
//reference: https://www.chartjs.org/docs/latest/axes/labelling.html
//padding: 30, //
//lineheight:30 //
}
}]
},
}
});
}
function generateandhandletemperaturedata() {
//todo: generate data
var data = [];
var currentdate = new date();
var starttime = currentdate.gettime() - 1*60*60*1000;
for(var i=starttime;i<currentdate.gettime();i+=(60*1000*15)){
data.push({
timestamp:i,
temperature: math.random()*30+1
})
}
handletemperaturedata(data);
}
function showtempgraph() {
generateandhandletemperaturedata()
// $.post("temperaturedata.php", handletemperaturedata);
}
body {
font-family: roboto;
background-color: #242e42;
color: white;
width: 98%;
}
#chart-container {
width: 100%;
height: 100%;
}
<html>
<head>
<title>temperatur</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.9.4/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/0.7.0/chartjs-plugin-datalabels.min.js"></script>
</head>
<body>
<div id="chart-container">
<canvas id="tempgraphcanvas" style="width:100%;height:100%;"></canvas>
</div>
</body>
</html>
Source: stackoverflow.com
Related Query
- ChartJS add text to canvas in linechart
- unable to add background color to the canvas using jspdf and chartjs
- Add background text in ChartJS
- How to add ChartJS code in Html2Pdf to view image
- Add Text to Doughnut Chart - ChartJS
- canvas fill text vanishes when hovering over chartjs pie chart
- How do I add time sourced from an external source as an X axis to a ChartJS graph?
- ChartJS - How to add Text between Pie Chart and Legend
- How to add text inside the doughnut chart using Chart.js?
- How to add labels into Chart.js canvas plugin?
- Truncating canvas labels in ChartJS while keeping the full label value in the tooltips
- How to modify chartjs tooltip so i can add customized strings in tooltips
- Adding Image inside Linechart points in ChartJs
- Canvas static height Chartjs
- ChartJS canvas not displaying rgba colors in IE, Safari and Firefox
- chartjs tooltip is cut off when out of canvas
- chartjs datalabels change font and color of text displaying inside pie chart
- Chartjs linechart with only one point - how to center
- How to add images as labels to Canvas Charts using chart.js
- ChartJS add tooltip to a grouped bar chart
- How to add text in centre of the doughnut chart using Chart.js?
- How to add label for ChartJs Legend
- How to add text at end of each line in charts.js
- ChartJS with AngularJS - Canvas won't display anything
- How to change the color of legend in chartjs and be able to add one more legend?
- Add a second Y-axis for Linechart in Chart.js?
- ChartJs canvas showing previous graph when changing Graph types
- How to add an empty data point to a linechart on Chart.js?
- Add zoom event handler to charts for chartjs with chartjs-plugin-zoom
- Chart.js - How to Add Text in the Middle of the Chart?
More Query from same tag
- Changing cursor to pointer on Chart.js bar chart when hover (mousemove) event is disabled?
- Who knows why I can't plot my chart properly?
- Why don't my datasets show up on line graph using Chart.js?
- Chart.js only draws when I go through debug on Chrome
- Calling a TypeScript function from a Chart.js option callback
- Adding a Date adapter for Time Cartesian axis from a cdn
- Add dynamically function to Chart.js
- jquery - How to update line chart.js with multiple datasets
- Obtain max value of y axis of line chart rendered with Chart.js
- How to add labels for only some of the data point?
- Change ChartJs axis title dynamically
- Chart.js: refresh second Y axis step on legend click
- ChartJS hover tooltip colors not showing their correct color
- How to put labels at 4 points of the day?
- Labels for Nested Doughtnut Chart React ChartJS
- Custom y axle using Chart.js
- Chart.js - Setting x-axis based on user input
- How to pass an array to chart.js data:[] while creating a chart in php
- Decimal in x-axis
- Chartjs custom dynamic legend overflowing
- ChartJS click on bar and change it's background color
- How can i implement RTL for Yaxis in Chartjs
- Showing 'undefined%' in the graph if data does not exist
- How to add datas to chart js from javascript array itself?
- How to draw x axis and y-axis origin line draw in ng2-google-charts?
- Using Chart.js on Angular 4
- ChartJS - Bottom labels displayed vertically
- Options: plugins not functioning
- How to position yAxes labels in chartJS
- Chart.js vertical line when hovering and shadow on line