javascriptcanvasjs

CanvasJS assign specific column color based on query value


How i can assign color es. red if $jsonArrayItem['x'] is equal to 'SpecificValue' etc etc ?

Thanks in advance for the help.

This is the code I use to create the column graph :

<php> 
        
    $jsonArray = array(); //create array for column data
    
    $sql = mysqli_query($conn, "SELECT DataAssistenza, COUNT(Arredatore) as y,
    Arredatore as x FROM assistenze WHERE YEAR(DataAssistenza) = YEAR(NOW())
    AND MONTH(DataAssistenza) = MONTH(NOW()) GROUP BY Arredatore ORDER BY Arredatore");
    
    while ($row = $sql->fetch_assoc()){
            $jsonArrayItem['y'] = $row['y']; // numeric value
            $jsonArrayItem['label'] = $row['x']; // person name
            array_push($jsonArray, $jsonArrayItem); //append the query data into the array
             
    }

>
<script>
window.onload = function() {
 
var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    theme: "light2",
    title:{
        text: ""
    },
    axisY: {
        title: "Numero Assistenze"
    },
    data: [{
        type: "column",
        yValueFormatString: "##",
        dataPoints: <?php echo json_encode($jsonArray, JSON_NUMERIC_CHECK); ?>
    }]
});
chart.render();
 
}
</script>

Rendering Graph


Solution

  • You can set color at datapoint level based on datapoint x value. Below is the updated JS code.

    <script>
    window.onload = function() {
     
    var chart = new CanvasJS.Chart("chartContainer", {
        animationEnabled: true,
        theme: "light2",
        title:{
            text: ""
        },
        axisY: {
            title: "Numero Assistenze"
        },
        data: [{
            type: "column",
            yValueFormatString: "##",
            dataPoints: <?php echo json_encode($jsonArray, JSON_NUMERIC_CHECK); ?>
        }]
    });
    
    //Set color at datapoint level if x === specificValue
    for(var i = 0; i < chart.options.data[0].dataPoints.length; i++) {
        if(chart.options.data[0].dataPoints[i].x === specificValue) {
            chart.options.data[0].dataPoints[i].color = "red";
        }
    }
    
    chart.render();
     
    }
    </script>