在饼图内显示百分比而不是计数。

huangapple go评论60阅读模式
英文:

Showing Percentage instead of count inside piechart

问题

I am using chart.js & chartjs-plugin-datalabels plugin.
Right now graph is showing count while hovering the graph and also inside the graph. But I want to show percentage inside the graph instead of count. How can I do that?

My codepen link - https://codepen.io/kaushik-kowboy/pen/BaGxKwy

<!DOCTYPE html>
<html>
<head>
  <title>Total Chart - Pie Chart with Labels</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
  <style>
    #totalChart{
        width: 400px !important;
        height: 400px !important;
    }
  </style>
</head>
<body>
  <div style="text-align: center;">
    <h2>Total Chart - Pie Chart with Labels</h2>
    <canvas id="totalChart" width="400" height="400"></canvas>
  </div>

  <script>
        var totalLabels = ["HD","SKY"];
        var totalData = ["138","251"];

        // Generate Facebook pie chart
        var facebookCtx = document.getElementById('totalChart');
        new Chart(facebookCtx, {
            type: 'pie',
            data: {
                labels: totalLabels,
                datasets: [{
                    label: 'no of Leads',
                    data: totalData,
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            },
            plugins: [ChartDataLabels],
                options: {
                        
                }
        });
  </script>
</body>
</html>

I have tried to display the percentage amount using ChartDataLabels, but I don't know how to do that. Right now only count is showing.

英文:

I am using chart.js & chartjs-plugin-datalabels plugin.
Right now graph is showing count while hovering the graph and also inside the graph. But I want to show percentage inside the graph instead of count. How can I do that?

My codepen link - https://codepen.io/kaushik-kowboy/pen/BaGxKwy

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Total Chart - Pie Chart with Labels&lt;/title&gt;
  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0&quot;&gt;&lt;/script&gt;
  &lt;style&gt;
    #totalChart{
        width: 400px !important;
        height: 400px !important;
    }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;div style=&quot;text-align: center;&quot;&gt;
    &lt;h2&gt;Total Chart - Pie Chart with Labels&lt;/h2&gt;
    &lt;canvas id=&quot;totalChart&quot; width=&quot;400&quot; height=&quot;400&quot;&gt;&lt;/canvas&gt;
  &lt;/div&gt;

  &lt;script&gt;
        var totalLabels = [&quot;HD&quot;,&quot;SKY&quot;];
        var totalData = [&quot;138&quot;,&quot;251&quot;];

        // Generate Facebook pie chart
        var facebookCtx = document.getElementById(&#39;totalChart&#39;);
        new Chart(facebookCtx, {
            type: &#39;pie&#39;,
            data: {
                labels: totalLabels,
                datasets: [{
                    label: &#39;no of Leads&#39;,
                    data: totalData,
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            },
            plugins: [ChartDataLabels],
                options: {
                        
                }
        });
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;```



I have tried to display the percentage amount using ChartDataLabels. but I don&#39;t know how to do that. Right now only count is showing.

</details>


# 答案1
**得分**: 0

Wherever u want to add Percentage ,you should write a map function.

instead of **totalData** use,

```javascript
totalData.map((ele)=>(ele/totalData.reduce(arrayTotal)*100))
datasets: [{
    label: 'no of Leads',
    data: totalData.map((ele)=>((ele/totalData.reduce(arrayTotal))*100)),
    borderWidth: 1
}]

I used reducer funtion,since i thought your chart data may be dynamic.
u can find the total of ur counts initially also.like write a seperate function which will find total of ur data.

below is the reducer function

function arrayTotal(total, num) {
  return total + num;
}

or u can find array total using a simple for loop which will iterate through and find total.

英文:

Wherever u want to add Percentage ,you should write a map function.

instead of totalData use,

totalData.map((ele)=&gt;(ele/totalData.reduce(arrayTotal)*100)
                datasets: [{
                    label: &#39;no of Leads&#39;,
                    data: totalData.map((ele)=&gt;((ele/totalData.reduce(arrayTotal))*100),
                    borderWidth: 1
                }]

I used reducer funtion,since i thought your chart data may be dynamic.
u can find the total of ur counts initially also.like write a seperate function which will find total of ur data.

below is the reducer function

function arrayTotal(total, num) {
  return total + num;
}

or u can find array total using a simple for loop which will iterate through and find total.

答案2

得分: 0

我终于找到了解决方案!

我只是更改了我的JavaScript代码,我将在下面附上它

// 生成总饼图
totalLabelss = ["HD","SKY"];
totalDatas = [138,251];

var totaldata = [{
data: totalDatas,
backgroundColor: [
"#4b77a9",
"#5f255f",
],
borderColor: "#fff",
label: ' No of Leads',
}];
var options = {
tooltips: {
enabled: false
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
const datapoints = ctx.chart.data.datasets[0].data
const total = datapoints.reduce((total, datapoint) => total + datapoint, 0)
const percentage = value / total * 100
return percentage.toFixed(0) + "%";
},
color: '#fff',
}
}
};
var totalCtxs = document.getElementById("totalChart").getContext('2d');
new Chart(totalCtxs, {
type: 'pie',
data: {
labels: totalLabelss,
datasets: totaldata
},
options: options,
plugins: [ChartDataLabels],
});

带有解决方案的CodePen链接 - https://codepen.io/kaushik-kowboy/pen/OJaBwZe

英文:

Finally I found the solution!

I just changed my js code that I will attach it below

// Generate Total pie chart
totalLabelss = [&quot;HD&quot;,&quot;SKY&quot;];
totalDatas = [138,251];
    
var totaldata = [{
  data: totalDatas,
  backgroundColor: [
    &quot;#4b77a9&quot;,
    &quot;#5f255f&quot;, 
  ],
  borderColor: &quot;#fff&quot;,
  label: &#39; No of Leads&#39;,
}];
var options = {
  tooltips: {
    enabled: false
  },
  plugins: {
    datalabels: {
      formatter: (value, ctx) =&gt; {
        const datapoints = ctx.chart.data.datasets[0].data
        const total = datapoints.reduce((total, datapoint) =&gt; total + datapoint, 0)
        const percentage = value / total * 100
        return percentage.toFixed(0) + &quot;%&quot;;
      },
      color: &#39;#fff&#39;,
    }
  }
};
var totalCtxs = document.getElementById(&quot;totalChart&quot;).getContext(&#39;2d&#39;);
new Chart(totalCtxs, {
      type: &#39;pie&#39;,
      data: {
      labels: totalLabelss,
        datasets: totaldata
      },
      options: options,
      plugins: [ChartDataLabels],
});

Code pen link with solution - https://codepen.io/kaushik-kowboy/pen/OJaBwZe

答案3

得分: 0

有时我们需要将数组数据转换为百分比数据,以在图表中使用,我们都在寻找一个最简单和最短的解决方案。

如何将数组中的数字转换为用于图表的百分比数组? 这相当简单。我们可以使用JavaScript的map原型和Math.max()函数来完成。以下是一个示例:

data = [12, 154, 56, 332, 44, 150, 120];
barH = 100;
max = Math.max(...data);
data = data.map(a => a == max ? barH : Math.round(barH - (a * barH / max)));
console.log(data);

首先,我们设置了最大百分比的柱形高度,最高可达100。

然后,我们查找数组中的最大值。

最后,我们创建了转换的映射。

脚本循环遍历数组,查找与最大值匹配的值。

如果有匹配项,则返回此数组值的最大柱高度。

如果没有匹配项,则获取相对于最大值的数组值的百分比比率并返回它。

简单地将您的值传递给数据数组,并查看控制台日志的输出。

英文:

Sometimes we need to convert array data into percentage data to be used in a graphs and aren't we all look for a simplest and shortest solution for that.

How do we convert array numbers into array percentages to be used in graphs? It is fairly simple. We can get it done by using JavaScript's map prototype and Math.max() functions. Here is an example;

        data = [12, 154, 56, 332, 44, 150, 120];
        barH = 100;  
        max = Math.max(...data); 
        data = data.map(a =&gt; a == max ? barH : Math.round(barH - (a * barH / max)));
        console.log(data);

Firstly, we set the bar height max percentage which can be be up to 100.

Then, we look for the max value in the array.

Finally, we create the map for conversion.

Script loops through the array and looks for value that matches the max value.

If there is a match, then returns the max bar height for this array value.

If there is no match, then getting the percentage ratio of the array value relative to max value and return it.

Simply, pass your values into data array and read what console.log outputs.

huangapple
  • 本文由 发表于 2023年7月18日 14:11:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709940.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定