달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2020. 1. 3. 09:30

Chart.js Pie 데이터 값 출력 개발/Chart.js2020. 1. 3. 09:30

반응형

어제 통계를 살펴보니, pie 데이터 값 출력이라는 정보를 찾는 키워드를 발견하여 글 작성합니다.

piece label이라는 Chart.js 확장 플러그인을 사용하면 되는데,

https://github.com/emn178/chartjs-plugin-labels/tree/master/src

위 링크를 타고 들어가면 js가 있습니다.

 

사용법은 아래와 같습니다.

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="/com/js/Chart.PieceLabel.js"></script> <!-- your piecelabel -->
<script type="text/javascript">
var num = Math.random();
  var data = {
      labels: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      datasets: [
          {
              data: [
                Math.random(),
                Math.random(), 
                Math.random(), 
                Math.random(), 
                Math.random(), 
                Math.random(), 
                Math.random(),
                Math.random(),
                Math.random(),
                Math.random()
              ],
              backgroundColor: [
      	        "#f79546",
       	        "#9bba57",
                "#4f81bb",
                "#5f497a",
                "#a94069",
                "#ff5f34",
                "#41774e",
                "#003663",
       	        "#49acc5",
       	        "#c0504e"
              ],
	          borderWidth: 0,
	          label: "Dataset 1"
          }]
  };
   
  window.onload = function() {
    var ctx8 = $('#chart8').get(0).getContext("2d");
    window.theChart8 = new Chart(ctx8, {
        type: 'pie',
        data: data,
        options: {
                responsive: true,
                legend: false,
                maintainAspectRatio : false,
                animation: false,
                pieceLabel: {
                  mode:"label",
                  position:"outside",
                  fontSize: 11,
                  fontStyle: 'bold'
               }
        }
    });
</script>
<div style="width:150px">
  <canvas id="chart8"></canvas>
</div>

간단히 설명하자면, options의 pieceLabel이 Pie 차트의 데이터 값을 표시하는 기능입니다.

mode에 따라 label/value/percentage(default)/image를 표시할 수 있고

position에 따라 default(default)/border/outside 값이 표시될 위치를 지정할 수 있습니다.

position : default / outside

또한, Pie 차트뿐만 아니라 Doughnut, polarArea, Bar 차트에서도 사용 가능합니다.

 

출처 : https://stackoverflow.com/questions/42164818/chart-js-show-labels-on-pie-chart

반응형
:
Posted by 리샤씨
반응형

지난번에 말한 대로 Chart.plugins.register를 이용해서 chart.js의 반도넛 차트 안에 숫자를 적을 수 있다.

방법은 다음과 같은 소스를 도넛 차트를 그리는 js에 넣고 도넛 차트 옵션에 elements.center를 만들면 된다.

(이전 포스팅 참조 : chart.js에서 반도넛 그래프 그리는 법)

Chart.plugins.register({
  beforeDraw: function (chart) {
	  if (chart.config.options.elements.center) {
	      //Get ctx from string
	      var ctx = chart.chart.ctx;

	      //Get options from the center object in options
	      var centerConfig = chart.config.options.elements.center;
	      var fontSize = centerConfig.fontSize || '50';
	      var fontStyle = centerConfig.fontStyle || 'Arial';
	      var txt = centerConfig.text;
	      var color = centerConfig.color || '#000';
	      var sidePadding = centerConfig.sidePadding || 20;
	      var sidePaddingCalculated = (sidePadding/100) * (chart.innerRadius * 2)
	      //Start with a base font of 30px
	      ctx.font = fontSize + "px " + fontStyle;

	      //Get the width of the string and also the width of the element minus 10 to give it 5px side padding
	      var stringWidth = ctx.measureText(txt).width;
	      var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

	      // Find out how much the font can grow in width.
	      var widthRatio = elementWidth / stringWidth;
	      var newFontSize = Math.floor(30 * widthRatio);
	      var elementHeight = (chart.innerRadius * 0.7);

	      // Pick a new font size so it will not be larger than the height of label.
	      var fontSizeToUse = Math.min(newFontSize, elementHeight);

	      //Set font settings to draw it correctly.
	      ctx.textAlign = 'center';
	      ctx.textBaseline = 'middle';
	      var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
	      var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);

	      //반도넛일 경우
	      if (chart.config.options.rotation === Math.PI && chart.config.options.circumference === Math.PI) {
	        centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 1.3);
	      }
	      ctx.font = fontSizeToUse+"px " + fontStyle;
	      ctx.fillStyle = color;

	      //Draw text in center
	      ctx.fillText(txt, centerX, centerY);
	    }
  }
});

 

 

만약 숫자가 너무 올라가있거나 내려가 있으면 38번 줄의 수식을 변경해주면 된다.

 

출처 : https://stackoverflow.com/questions/20966817/how-to-add-text-inside-the-doughnut-chart-using-chart-js

반응형
:
Posted by 리샤씨
2017. 12. 12. 09:55

Chart.js에서 반도넛 그래프 그리는 법 개발/Chart.js2017. 12. 12. 09:55

반응형

 

Chart.js에서 반도넛(Half Donuts) 그래프를 그리는 법은 그냥 도넛 차트 옵션에

아래와 같이 rotation: 1 * Math.PI, circumference: 1 * Math.PI를 추가해주면 된다.

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script> 
<script type="text/javascript" charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script> 
<script type="text/javascript"> 
var num = Math.random(); 
	var data = { 
		labels: [ 
			"pink" 
		], 
		datasets: [ 
			{ 
				data: [num, 1-num], 
				backgroundColor: [ 
					"#FF6384"
 				], 
				hoverBackgroundColor: [ 
					"#FF6384" 
				] 
			}] 
		}; 
	window.onload = function() { 
		var ctx8 = $('#chart8').get(0).getContext("2d"); 
		window.theChart8 = new Chart(ctx8, { 
			type: 'doughnut', 
			data: data, 
			options: { 
				responsive: true, 
				legend: { 
					display: false 
				}, 
				elements: { 
					center: { 
						text: Math.round(num*100), 
						fontStyle: 'Helvetica', //Default Arial 
						sidePadding: 15 //Default 20 (as a percentage) 
					}
				}, 
				maintainAspectRatio : false, 
				cutoutPercentage:70, 
				animation:false, 
				rotation: 1 * Math.PI, 
				circumference: 1 * Math.PI 
			} 
		}); 
</script> 
<div style="width:150px"> 
	<canvas id="chart8"></canvas> 
</div>

그리고 다음과 같이 가운데에다 숫자를 적고 싶게 될 수 있는데 

그것은 Chart.plugins.register를 사용해야 하므로 다음 포스팅에서 설명하겠다.

(위의 옵션에서 elements안의 center가 Chart.plugins.register를 이용해서 만든 옵션이다) 

 

출처 : https://laracasts.com/discuss/channels/general-discussion/chartjs-and-half-donuts

 

반응형
:
Posted by 리샤씨


반응형
반응형