달력

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
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 리샤씨
반응형

chart.js로는 스크롤을 해도 y축이 보이게 하는 기능을 제공해주진 않지만 임의로 비슷하게 만들 수 있다. 

바로 canvas의 drawImage를 이용하는 방법이다. (물론 약간의 css기술도 필요하다)

아래의 코드처럼 animation이 끝났을 때 canvas의 drawImage를 이용하여 y축을 복사하면 된다.

<style type="text/css">
.chartWrapper {
  position: relative;
  top:15%;
}

.chartWrapper > canvas {
  position: absolute;
  left: 0;
  top: 0;
  pointer-events: none;
}

.chartAreaWrapper {
  overflow-x: scroll;
}
.chartAreaWrapper2 {
  width: 10000px;
}

</style>


<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 chartData = {
        labels: ["label1", "label2", "label3", "label4", "label5", "label6", "label7", "label8", "label9", "label10", "label11", "label12", "label13", "label14", "label15", "label16"],
        datasets: [{
            type: 'line',
            label: 'line',
            borderColor: "#FF6384",
            borderWidth: 2,
            fill: false,
            lineTension: 0,
            data: [
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10,
                Math.random()*10
            ]
        }, {
            type: 'bar',
            label: 'bar',
            backgroundColor: "#36A2EB",
            data: [
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000,
                Math.random()*25000
            ],
            borderColor: 'white',
            borderWidth: 2
        },]

    };
	
   $.fn.hasScrollBar = function() {
	    return (this.prop("scrollHeight") == 0 && this.prop("clientHeight") == 0)
	            || (this.prop("scrollHeight") > this.prop("clientHeight"));
   };

    window.onload = function() {
		var ctx9 = $('#chart9').get(0).getContext("2d");
		var ctx9Axis = $('#chart9Axis').get(0).getContext("2d");
		var ctx9Axis2 = $('#chart9Axis2').get(0).getContext("2d");
		
		changeChartLength(chartData);
		
		window.theChart9 = new Chart(ctx9, {
            type: 'bar',
            data: chartData,
            options: {
                responsive: true,
                scales: {
                	xAxes: [{
                		barThickness:50,
               		    gridLines: {
               		      display: false
               		    },
                        offset:true
                    }],
                    yAxes: [{
                        id: 'em',
                        type: 'linear',
                        poition: 'left',
                        ticks: {
	                        max: 25000,
	                        min: 0,
	                        stepSize: 5000
                        },
                        gridLines: {
                		    drawBorder: false//축과 데이터의 경계선 표시 여부
                		  }
                      }, {
                        id: 'ppm',
                        type: 'linear',
                        position: 'right',
                        ticks: {
                          max: 10,
                          min: 0,
	                      stepSize: 2
                        },
                        gridLines: {
                		    drawBorder: false//축과 데이터의 경계선 표시 여부
                		  }
                      }]
                },
                animation: {
    	            onComplete: function (animation) {
    	            	var sourceCanvas = ctx9.canvas;
    	            	var copyWidth = this.scales["em"].width;
    	            	var copyWidth2 = this.scales["ppm"].width;
    	            	var copyHeight = this.chart.height;
    	            	var targetElementWidth = ctx9.canvas.clientWidth;
    	                var targetElementHeight = ctx9.canvas.clientHeight;
    	                
    	            	ctx9Axis.canvas.width = copyWidth;
    	            	ctx9Axis.canvas.height = copyHeight;
    	            	
    	            	ctx9Axis.drawImage(sourceCanvas, 0, 0, targetElementWidth, targetElementHeight);

    	            	ctx9Axis2.canvas.height = copyHeight;
    	            	
    	            	var tmp = $("body").hasScrollBar() ? 16 : 0;
                        ctx9Axis2.canvas.width = targetElementWidth > window.innerWidth-tmp ? window.innerWidth-tmp : targetElementWidth;
                        ctx9Axis2.drawImage(sourceCanvas, 
                              				sourceCanvas.width - copyWidth2-15, 
                            				0, 
                            				copyWidth2+15, 
                            				sourceCanvas.height, 
                            				ctx9Axis2.canvas.width - copyWidth2 - 13.5 + (sourceCanvas.height - ctx9Axis2.canvas.height)/15, 
                            				0, 
                            				copyWidth2 + 13.5 - (sourceCanvas.height - ctx9Axis2.canvas.height)/15, 
                            				copyHeight);
    	            }
                }
            }
    });
</script>
<div class="chartWrapper">
	<div class="chartAreaWrapper">
		<div class="chartAreaWrapper2">
			<canvas id="chart9">
		</div>
	</div>

	<canvas id="chart9Axis" height="300" width="32">
	<canvas id="chart9Axis2" height="300" width="32">
</div>

 

ctx9Axis는 왼쪽 y축을 위한 canvas context이고

ctx9Axis2는 오른쪽 y축을 위한 canvas context이므로 필요한 대로 가져다가 쓰시면 된다.

 

참고 출처 : https://stackoverflow.com/questions/47038946/chartjs-v2-on-retina-display-has-label-size-issue-text-is-too-large

반응형
:
Posted by 리샤씨
2017. 11. 29. 10:06

Chart.js를 이용해 막대 그래프 그리기 개발/Chart.js2017. 11. 29. 10:06

반응형
<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.7.1/Chart.min.js"></script> 
<script type="text/javascript"> 
var barChartData = {        
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: 'Pass',
            backgroundColor: "#1E90FF",
            data: [
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000
           ]
        }, {
            label: 'NG',
            backgroundColor: "#F7464A",
            data: [
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000,
                Math.random()*90000
            ]
        }]
    };
 window.onload = function() {
    var ctx = $('#chart').get(0).getContext("2d"); 
    window.theChart = new Chart(ctx, {
         type: 'bar',
         data: barChartData,
         options: {
            
         }
 });
}
</script>
<canvas id="chart"></canvas> 

 

위 코드를 실행하면 아래와 같은 차트가 화면에 꽉 차게 그려지는데

canvas를 감싸는 div를 만들어 그 div에 크기를 정해주면 차트 크기를 조정할 수도 있고 

options를 이용해 이미 정의된 방법으로 차트를 조정할 수도 있고

Chart.plugins.register를 이용해 필요한 차트 option을 만들 수도 있다.

 

 

 

반응형
:
Posted by 리샤씨


반응형
반응형