score:1

Accepted answer

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);
}

weather station

score:1

you could attempt to manually write on the canvas using js, however the example below modifies your code to

  1. move the axis to the left
  2. 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>


Related Query

More Query from same tag