在Chart JS生成的图形中绘制数据

Draw data in graphics generated by Chart JS

下午好。 我正在使用 Chart JS,我正在尝试在条形图中显示每列的现有总数。

在后端,我使用 Laravel 作为框架,我通过 $datacount 变量从控制器传递数据。

这是我在控制器中的查询:

$datacount = DB::table('topics')
            ->leftJoin('proposals_topics', 'topics.id', '=', 'proposals_topics.topic_id')
            ->select('topics.name as tpcname', 'proposals_topics.topic_id', \DB::raw('count(topic_id) as total'))
            ->groupBy('topics.name', 'proposals_topics.topic_id')
            ->orderBy('topic_id', 'desc')
            ->get();

我在这个脚本中收到的变量数据:

<script>
   var datacount = <?= json_encode($datacount, JSON_PRETTY_PRINT); ?>;

   console.log(datacount);

   // Bar chart
   new Chart(document.getElementById("bar-chart"), {
       type: 'bar',
       data: {
       labels: ["Compras y Contrataciones", "Acceso a la Información", "Educación", "Organismos de Control", "Servicio Civil", "Infraestructura", "Energía", "Gestión Financiera", "Salud", "Agua"],
       datasets: [
           {
           label: "Cantidad generada",
           backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#ffc344","#ff8e17", "#ff4cd8","#ffea4c","#b7ff4c"],
           data: [datacount.total]
           }
       ]
       },
       options: {
       legend: { display: false },
       title: {
           display: true,
           text: 'Datos generados por eje temático.'
       }
       }
    });
</script>

我在控制台收到结果,但我无法显示数组的数据。

您可以将 PHP 脚本中的数据放入您的数据字段中:

在阅读了一些关于 Laravel 文档和 Javascript 之后,我找到了在图表上绘制数据的解决方案。

在脚本中,我根据 https://laravel.com/docs/5.7/blade#if-statements.

的循环文档构建了 foreach
<script>        
  //console.log(datacount);

  // Bar chart
  new Chart(document.getElementById("bar-chart"), {
      type: 'bar',
      data: {
      labels: [
          @foreach($datacount as $dt)
              "{{ $dt->tpname }}",
          @endforeach
      ],
      datasets: [
          {
          label: "Cantidad generada",
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#ffc344","#ff8e17", "#ff4cd8","#ffea4c","#b7ff4c"],
              data: [
                  @foreach($datacount as $dt)
                      {!! $dt->total !!},
                  @endforeach
              ],
           }
      ]
      },
      options: {
      legend: { display: false },
      title: {
          display: true,
          text: 'Ejes temáticos por cantidad de propuestas.'
      }
      }
    });
</script>

还可以在以下位置查看一些示例:https://quickadminpanel.com/pages/reports-generator-module