Chapter 6 Additional examples

6.1 Simple bar plot

For PHP:

// Wert/Ergebnis ermitteln
// variable1
$variable1= valueMean(array(
'var_01', 
'var_02', 
'var_03', 
'var_04', 
'var_05', 
'var_06' 
));
debug($variable1);

// Wert/Ergebnis ermitteln
// variable2
$variable2= valueMean(array(
'var_07', 
'var_08', 
'var_09', 
'var_10', 
'var_11', 
'var_12' 
));
debug($variable2);


replace('%variable1%', sprintf('%1.1f', $variable1));
replace('%variable2%', sprintf('%1.1f', $variable2));

For HTML:

<!-- Include the Chart.js library -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Create a canvas element to render the chart -->
<canvas id="barChart"></canvas>

<script>
  // Get the context of the canvas element
  var ctx = document.getElementById('barChart').getContext('2d');

  // Create a new bar chart
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['variable1', 'variable2'],
      datasets: [{
        data: ['%variable1%', '%variable2%']
        backgroundColor: 'rgba(178, 24, 43, 0.2)',
        borderColor: 'rgba(178, 24, 43, 1)',
        borderWidth: 1.5
      }]
    },
    options: {
      scales: {
        y: {
          min: 1,
          max: 7
        }
      },
      plugins: {
        legend: { display: false }
      }
    }
  });
</script>

6.2 Simple radar plot

For HTML (PHP-code for the simple radar plot is idential to PHP-code of the simple bar plot):

<!-- Create a canvas element to render the chart -->
<canvas id="radarChart"></canvas>

<script>
  // Get the context of the canvas element
  var ctx = document.getElementById('radarChart').getContext('2d');

  // Create a new radar chart
  new Chart(ctx, {
    type: 'radar',
    data: {
      labels: ['Label1', 'Label2'],
      datasets: [{
        data: ['%variable1%', '%variable2%']
      }]
    }
  });
</script>

6.3 Comparable bar plot with hatching and error bars

For HTML (PHP-code for the simple radar plot is idential to PHP-code of the simple bar plot):

<!-- Include the Chart.js library -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Create a canvas element to render the chart -->
<canvas id="barChart"></canvas>

<script>
  // Get the context of the canvas element
  var ctx = document.getElementById('barChart').getContext('2d');



const HatchingAndErrorBars = {
  id: 'HatchingAndErrorBars',
  afterDraw: (chart) => {
    const { ctx } = chart;
    const datasetIndex = 1; // Comparative Study Data is the second dataset
    const meta = chart.getDatasetMeta(datasetIndex);
    const yAxis = chart.scales['y'];
    const errorValues = [1.12, 0.97]; // Replace with your error values
    
    // Calculate the pixel for y value 1
    const yForOne = yAxis.getPixelForValue(1);
    
    // Draw hatching
    meta.data.forEach((bar) => {
      const { x, y, width } = bar.getProps(['x', 'y', 'width']);
      ctx.save();
      ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
      ctx.beginPath();
      for (let i = y; i < yForOne; i += 20) {
        let endY = i + 10;
        if (endY > yForOne) {
          endY = yForOne;
        }
        ctx.moveTo(x - width / 2, i);
        ctx.lineTo(x + width / 2, endY);
      }
      ctx.stroke();
      ctx.restore();
    });

    // Draw error bars
    meta.data.forEach((bar, index) => {
      const { x, y } = bar.getProps(['x', 'y']);
      const error = errorValues[index];
      const yWithError = yAxis.getPixelForValue(chart.data.datasets[datasetIndex].data[index] + error);
      const yWithErrorMin = yAxis.getPixelForValue(chart.data.datasets[datasetIndex].data[index] - error);

      ctx.save();
      ctx.strokeStyle = 'black';
      ctx.lineWidth = 1;

      // Draw the top cap
      ctx.beginPath();
      ctx.moveTo(x - 5, yWithError);
      ctx.lineTo(x + 5, yWithError);
      ctx.stroke();

      // Draw the bottom cap
      ctx.beginPath();
      ctx.moveTo(x - 5, yWithErrorMin);
      ctx.lineTo(x + 5, yWithErrorMin);
      ctx.stroke();

      // Draw the vertical line
      ctx.beginPath();
      ctx.moveTo(x, yWithError);
      ctx.lineTo(x, yWithErrorMin);
      ctx.stroke();
      ctx.restore();
    });
  }
};

  // Create a new bar chart
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['variable1', 'variable2'],
      datasets: [{
      
      //participant data
        data: ['%variable1%', '%variable2%']
        backgroundColor: 'rgba(178, 24, 43, 0.2)',
        borderColor: 'rgba(178, 24, 43, 1)',
        borderWidth: 1.5
      },
      
      //comparable data
        {
          label: 'Data',
          data: [5.09, 4.85],
          borderWidth: 1.5
        }
      ]
    },
      

   //options
    options: {
        scales: {
            y: {
                min: 1,
                max: 7,
                ticks: {
                    font: {
                        size: 18
                    }
                }
            }
        },
      plugins: {
        legend: {
          display: false
        }
      }
    },
    plugins: [HatchingAndErrorBars]
  });
</script>

6.4 Multiple bar plot with normalization

For PHP:

// Initialize arrays for scale ranges
// Here I specify the length of each scale
$scale_ranges = array(
    'Achtsamkeit' => 4,
    'Lebenszufriedenheit' => 7,
    'Prokastination' => 4,
    'Selbstwirksamkeit' => 4,
    'PolitischeSelbstwirksamkeit' => 7,
    'BerufsUndOrganisationsklima' => 6
);

// Initialize arrays for values of each scale
$scale_values = array(
    'Achtsamkeit' => array(value('VA07_01'), value('VA07_02'), value('VA07_03'), value('VA07_04'), value('VA07_05'), value('VA07_06'), value('VA07_07'), value('VA07_08'), value('VA07_09'), value('VA07_10'), value('VA07_11'), value('VA07_12'), value('VA07_13'), value('VA07_14')),
    'Lebenszufriedenheit' => array(value('VA01_01'), value('VA01_02'), value('VA01_03'), value('VA01_04'), value('VA01_05')),
    'Prokastination' => array(value('VA09_01'), value('VA09_02'), value('VA09_03'), value('VA09_04'), value('VA09_05'), value('VA09_06'), value('VA09_07'), value('VA09_08'), value('VA09_09')),
    'Selbstwirksamkeit' => array(value('VA10_01'), value('VA10_02'), value('VA10_03'), value('VA10_04'), value('VA10_05'), value('VA10_06'), value('VA10_07'), value('VA10_08'), value('VA10_09'), value('VA10_10')),
    'PolitischeSelbstwirksamkeit' => array(value('VA02_01'), value('VA02_02'), value('VA02_03'), value('VA02_04'), value('VA02_05'), value('VA02_06'), value('VA02_07'), value('VA02_08'), value('VA02_09'), value('VA02_10')),
    'BerufsUndOrganisationsklima' => array(value('VA08_01'), value('VA08_02'), value('VA08_03'), value('VA08_04'), value('VA08_05'), value('VA08_06'), value('VA08_07'), value('VA08_08'))
);

// Loop through each scale and its values
foreach ($scale_values as $scale => $values) {
    $sum = 0;
    $count = 0;
    foreach ($values as $value) {
        if ($value >= 0) {
            $sum += (int)$value; // Cast to int to avoid operand type issues
            $count++;
        }
    }
    if ($count > 0) {
        $mean = $sum / $count;
        // Normalize the mean
        $normalized_mean = ($mean - 1) / ($scale_ranges[$scale] - 1);
        replace('%' . $scale . '%', sprintf('%1.1f', $normalized_mean));
    } else {
        replace('%' . $scale . '%', 'NaN');
    }
}

For HTML:

<!-- Include the Chart.js library -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Create a canvas element to render the chart -->
<canvas id="barChart"></canvas>

<script>
  // Get the context of the canvas element
  var ctx = document.getElementById('barChart').getContext('2d');

  // Create a new bar chart
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Achtsamkeit', 'Lebenszufriedenheit', 'Prokastination', 'Selbstwirksamkeit', 'Politische Selbstwirksamkeit', 'Berufs- und Organisationsklima'],
      datasets: [{
        data: ['%Achtsamkeit%', '%Lebenszufriedenheit%', '%Prokastination%', '%Selbstwirksamkeit%', '%PolitischeSelbstwirksamkeit%', '%BerufsUndOrganisationsklima%'],
        fill: true,
backgroundColor: [
  'rgba(178, 24, 43, 0.2)',
  'rgba(33, 102, 172, 0.2)',
  'rgba(0, 128, 0, 0.2)',
  'rgba(255, 0, 0, 0.2)',
  'rgba(255, 127, 0, 0.2)',
  'rgba(106, 61, 154, 0.2)'
],
borderColor: [
  'rgba(178, 24, 43, 1)',
  'rgba(33, 102, 172, 1)',
  'rgba(0, 128, 0, 1)',
  'rgba(255, 0, 0, 1)',
  'rgba(255, 127, 0, 1)',
  'rgba(106, 61, 154, 1)'
        ],
        borderWidth: 1.5
      }]
    },
    options: {
      scales: {
        x: {
          ticks: {
            maxRotation: 45,
            minRotation: 45
          }
        },
        y: {
          min: 0,
          max: 1,
          pointLabels: {
            font: {
              size: 18
            }
          }
        }
      },
      plugins: {
        legend: {
          display: false
        }
      }
    }
  });
</script>

6.5 Download any plot as PDF

For HTML(PHP-code is idential to any of the previous examples. This HTML Chunck goes on top of you existing HTML code):

<!-- Include the jsPDF and html2canvas libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>

<!-- Add a button for downloading PDF -->
<button id="downloadPdf">Download PDF</button>

<script>
  // Add event listener for the button
  document.getElementById('downloadPdf').addEventListener('click', function() {
    html2canvas(document.getElementById('barChart'), {
      onrendered: function(canvas) {
        var imgData = canvas.toDataURL('image/png');
        var pdf = new jsPDF();
        pdf.addImage(imgData, 'PNG', 10, 10);
        pdf.save('download.pdf');
      }
    });
  });
</script>