将百分比添加到标签徽章-甜甜圈chart.js [英] Add percentage to label badge - doughnut chart.js

查看:57
本文介绍了将百分比添加到标签徽章-甜甜圈chart.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做很多研究,但无法弄清楚如何在标签标记中输入百分比,如下图所示.

更新:我正在使用这个laravel包装器:

解决方案

即使我做了很多研究,在chartjs库中都找不到针对这种行为的任何东西,所以想出了一个办法.

Hack是类似的,不要让chart js绘制图例,相反,我们只是从chart js库中获取图例的HTML,并将其放在我们的容器中.这样,我们就可以完全访问图例,并且我们可以做任何我们想做的事情.

https://jsfiddle.net/1kxenzpr/

  const data = [70,30,0];调试器;var ctx = document.getElementById("myChart").getContext('2d');var chart = new Chart(ctx,{类型:派",数据: {标签:[绿色",蓝色",灰色",紫色",黄色",红色",黑色"],数据集:[{背景颜色: [#2ecc71",#3498db",#95a5a6",#9b59b6",#f1c40f",#e74c3c",#34495e"],数据:数据}]},选项: {传奇: {显示:假},}});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 {宽度:80%;保证金:15px自动;}[class $ =-legend"] {列表样式:无;光标:指针;padding-left:0;}[class $ =-legend"] li {显示:inline-block;填充:0 5px;}[class $ =-legend"] li.hidden {文字装饰:直行;}[class $ =-legend"] li span {显示:inline-block;右边距:10px;宽度:50像素;font-size:12px;文本对齐:居中;}  

 < 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>  

I've been doing a lot of research but I wasn't able to figure out, how to enter percentage into labels badge like this image below.

update: I'm using this laravel wrapper : https://github.com/ConsoleTVs/Charts so was the reason I didn't want to confuse viewers. I just want to know the name of the option.. my code is this:

$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,
        ]);

the first image the current result and the second is what I wanted. thanks in advance.

解决方案

Even I researched a lot, couldn't find anything for this kind of behavior in chartjs library, So come up with a hack.

Hack is something like, Do not let chart js to draw legends, Instead we just get the HTML of legends from chart js library, and put it in our container. By doing this we have full access of legends and we can do whatever we want.

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>

这篇关于将百分比添加到标签徽章-甜甜圈chart.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆