将百分比添加到标签徽章- doughnut chart.js

ccgok5k5  于 2023-11-18  发布在  Chart.js
关注(0)|答案(2)|浏览(179)

我不能够弄清楚,如何输入百分比到标签徽章像下面的图片.
我使用的是laravel的 Package 器:https://github.com/ConsoleTVs/Charts,这就是我不想让观众感到困惑的原因。
我只想知道选项的名称。
我的代码是这样的:

$perTopicChart = (new AnsweredPerTopic);//->percentageInnerCutout(70);
    $perTopicChart->options([
        "events" => [],
        "legend" => [
            "labels" => [
                "defaultFontFamily" => "Tahoma",
                "fontSize" => 16,
            ],
            "position" => 'bottom'
        ],
        "cutoutPercentage" => 80,
        'tooltips' => [
            "show" => true
        ]
    ])->displayAxes(0);

    // put the labels (keys)
    $perTopicChart->labels($keys->map(function ($q) use ($perTopic) {
        $topic = Topic::find($q);
        $str = $topic->name;
        foreach ($perTopic as $key => $value) {
            if ($key == $q) {
                $str .= ' ' . round($value) . '%';
            }
        }
        return "topic name " . '-'. $topic->id;
         
    })->push('other'))
    ->options([]);
    // get random color 
    // $color = RandomColor::many(count($keys), array(
    //     'luminosity' => 'bright',
    //     'hue' => ['pink', 'green', 'orange'] // e.g. 'rgb(225,200,20)'
    //     ));
    $color = [
        "#38c172",
        "#9F9",
        "#Fa0",
        "pink",
        "red",
    ];
    
    $perTopicChart->dataset("Practice per Category", "doughnut", $values->map(function ($q) {
        return round($q);
    })->push($remainingPercenteg))
        ->backgroundColor($color)
        ->options([
            'borderWidth' => 2.5,
        ]);

字符串
第一个图像是当前的结果,第二个是我想要的。
100d1x

的字符串

zzlelutf

zzlelutf1#

即使我研究了很多,在chartjs库中也找不到这种行为的任何东西,所以想出一个黑客。
哈克是什么样的,不要让图表js来绘制图例,相反,我们只是从图表js库中获取图例的HTML,并把它放在我们的容器中.通过这样做,我们有充分的图例访问,我们可以做任何我们想要的.
https://jsfiddle.net/1kxenzpr/

const data = [70, 30, 0];
debugger;
var ctx = document.getElementById("myChart").getContext('2d');
var chart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["Green", "Blue", "Gray", "Purple", "Yellow", "Red", "Black"],
    datasets: [{
      backgroundColor: [
        "#2ecc71",
        "#3498db",
        "#95a5a6",
        "#9b59b6",
        "#f1c40f",
        "#e74c3c",
        "#34495e"
      ],
      data: data
    }]
  },
  options: {
    legend: {
      display: false
    },
  }
});
var myLegendContainer = document.getElementById("legend");
myLegendContainer.innerHTML = chart.generateLegend();
var legendItems = myLegendContainer.getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i++) {
  legendItems[i].querySelectorAll('span')[0].innerHTML = data[i] + '%'
}
.container {
  width: 80%;
  margin: 15px auto;
}

[class$="-legend"] {
  list-style: none;
  cursor: pointer;
  padding-left: 0;
}

[class$="-legend"] li {
  display: inline-block;
  padding: 0 5px;
}

[class$="-legend"] li.hidden {
  text-decoration: line-through;
}

[class$="-legend"] li span {
  display: inline-block;
  margin-right: 10px;
  width: 50px;
  font-size: 12px;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

<div class="container">
  <div>
    <canvas id="myChart"></canvas>
    <div id="legend"></div>
  </div>
</div>
zqdjd7g9

zqdjd7g92#

不行(通过设置X或Y),应该使用legendCallback:https://www.chartjs.org/docs/latest/configuration/legend.html#html-legends

无论如何,这是+-想法(通过基本JS转换为%)。要向前迈出这一步,您应该生成完整生成HTML图例(将数字放入颜色div中)。相关:Custom Legend with ChartJS v2.0

var myData = [4, 9, 5];

var data = {
  labels: ["Africa", "Asia", "Europe"],
  datasets: [{
    label: "Population (millions)",
    backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f"],
    data: myData
  }]
};

/* get total */
const reducer = (accumulator, currentValue) => accumulator + currentValue;
var total = myData.reduce(reducer);

var options = {
  responsive: true,
  title: {
    text: 'Show % calucate on fly',
    position: 'top',
    display: true
  },
  legend: {
    display: true,
    labels: {
      /* generateLabels */
      generateLabels(chart) {
        const data = chart.data;
        if (data.labels.length && data.datasets.length) {
          /* inner loop throw lables */
          return data.labels.map((label, i) => {
            var backgroundColor = data.datasets[0].backgroundColor[i];
            var current = data.datasets[0].data[i];
            var percentage =  ((current * 100) / total).toFixed(2) + '%'; 
            return {
              text: label + " | " + percentage,
              fillStyle: backgroundColor,
              // Extra data used for toggling the correct item
              index: i
            };
          });
        }
        return [];
      }

    },

  },
  scales: {
    xAxes: [{
      display: true
    }],
    yAxes: [{
      display: true
    }]
  }
};

new Chart(document.getElementById("chart"), {
  type: 'pie',
  data: data,
  options: options
});

个字符

相关问题