달력

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

※ 해당 글은 아래 글과 연결되어 있습니다.

혹시 잘 안되거나 이해 안 되는 부분이 있으시면 아래 글을 참조하여 주세요.

http://risha-lee.tistory.com/18?category=764955

 

 

 

앞서 말했다시피 사용자 범례를 이전 글처럼 만들기만 해서는 

위 그림처럼 범례 클릭 시 해당 데이터셋의 숨김/보이기 토글 기능을 사용할 수 없다.

 

해당 기능을 만들려면 이전 글의 코드에 다음과 같이 추가로 코드를 작성해주어야 한다.

 

<script>
	 window.onload = function() {
		$("#chartLegend li").click(function(){
			updateDataset(event, $(this).attr("datasetIndex"), "theChart");
			if($(this).css("text-decoration").indexOf("line-through")<0){
				$(this).css("text-decoration", "line-through");
			} else{
				$(this).css("text-decoration", "none");
			}
		});
	 }

	 //범례 클릭시 해당 데이터셋이 숨김/보이기 토글 기능 함수
	 function updateDataset(e, datasetIndex, chartId) {
		var index = datasetIndex;
		var ci = e.view[chartId];
		var meta = ci.getDatasetMeta(index);
		var scaleList = ci.options.scales["yAxes"];
        
		meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
		ci.update();
	 }
</script>

 

참고 : https://github.com/chartjs/Chart.js/issues/2565

 

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

Chart.js가 기본적으로 제공하는 범례는 그냥 위치를 위나 아래로 정하면 무조건 가운데 정렬만 할 뿐,

왼쪽 위. 오른쪽 위, 오른쪽 아래, 왼쪽 아래 등 위치를 자유자재로 변경할 수 없어서 

오른쪽 위에 범례를 두기 위해 사용자 범례를 사용했었다.

물론 디자인도 자유자재로 변경할 수 있다는 점이 마음에 들어서 위치를 바꿀 겸 범례의 디자인도 조정하였다.

 

추가로 덧붙이자면 Chart.js에서 제공하는 기본 범례를 사용하면 그래프가 길어져 스크롤이 생겼을 때,

스크롤 위치에 따라 어떤 부분에서는 범례가 보이지만 어떤 부분에서는 범례가 보이지 않을 수 있다.

사용자 범례를 사용하면 위의 문제점도 해결해준다. (차트를 좌우로 스크롤해도 범례의 위치는 고정된다)

 

1. 막대 차트&막대 라인 차트 - 막대 형식 데이터셋 원형, 라인 형식 데이터셋 선형 범례

2. 라인 차트 - 라인 형식 데이터셋 사각형 범례

 

별다른 설정 없이 막대 차트냐, 라인 차트냐, 해당 데이터셋의 형식이 라인이냐 바이냐에 따라 자동으로 class를 입히도록 작성하였다.

아래의 코드를 사용하면 위와 같은 범례를 만들 수 있다. 예제는 막대 라인 차트이다. 

 

<style type="text/css">
.chartjs-legend ol,
.chartjs-legend ul {
  list-style: none;
  margin:0;
  padding:0;
  text-align:right;
}

.chartjs-legend li {
  cursor:pointer;
  display: inline-table;
  margin: 10px 4px;
}

.chartjs-legend li span.bar{
  position:relative;
  padding: 0px 10px;
  margin: 5px;
  border-radius:100px;
  color:white;
}

.chartjs-legend li span.line{
  position:relative;
  padding: 1px 10px;
  margin: 5px;
  color:white;
}

.chartjs-legend li div.line{
	float:left;
	height:2px;
	background:#000;
	font-size:0;
	line-height:0;
	width:25px;
	padding:1px 0px;
	border-radius:100px;
	margin: 9px 5px;
}
</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>       
	var barChartData = {        
	        labels: ["January", "February", "March", "April", "May", "June", "July"],
	        datasets: [{
	            type: 'line',
	            label: 'line',
	            borderColor: "#1E90FF",
	            fill: false,
	            data: [
	                Math.random()*90000,
	                Math.random()*90000,
	                Math.random()*90000,
	                Math.random()*90000,
	                Math.random()*90000,
	                Math.random()*90000,
	                Math.random()*90000
	           ]
	        }, 
	        {
	            type: 'bar',
	            label: 'bar',
	            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: {
	             legend: false,
	             legendCallback: function(chart){
	                return drawCustomLegend(chart);
	             }// 사용자 범례를 만들 때 쓰는 함수를 지정하거나 작성한다.
	         }
	    });
	    $('#chartLegend').html(window.theChart.generateLegend());//사용자 범례 자리에 해당 차트에 대한 사용자 범례 코드를 넣는다.
	 }
	 
	 function drawCustomLegend(chart){
    	var text = [];
    	text.push('<ul class="' + chart.id + '-legend">');
    	if(chart.config.type == 'bar'){//막대차트, 막대라인차트일 경우
    		var barIndex = chart.data.datasets.length;
        	for (var i = 0; i <chart.data.datasets.length; i++) {
        		if(chart.data.datasets[i].type == 'line' == false){
        			barIndex = i;
        			break;
        		}
        	}//라인 형식 데이터셋이 어디까지인지 확인
        	// -> 막대 형식의 데이터셋을 라인 형식의 데이터셋보다 앞에 둘 경우 라인이 막대에 묻히기 때문에 라인 형식이 먼저 올 수 밖에 없다.
        	//그러나 막대 형식의 데이터셋의 범례를 먼저 그리고 싶었기 때문에 해당 작업을 했다.
        	
        	for (i = barIndex; i <chart.data.datasets.length; i++) {
        		if(!(chart.data.datasets[i].hideLegend) && chart.data.datasets[i].label){
        			text.push('<li  datasetIndex="'+i+'"><span class="bar" style="background-color:' + chart.data.datasets[i].backgroundColor + '" ></span>');
        			text.push('<span>'+chart.data.datasets[i].label+'</span>');
        			text.push('</li>');
        		} 
        	}//막대 형식 데이터셋의 범례를 먼저 그림
        	
        	for (i = 0; i <barIndex; i++) {
        		if(!(chart.data.datasets[i].hideLegend) && chart.data.datasets[i].label){
        			text.push('<li datasetIndex="'+i+'"><div class="line" style="background:' + chart.data.datasets[i].borderColor + '"></div>');
        			text.push('<span>'+chart.data.datasets[i].label+'</span>');
        			text.push('</li>');
        		} 
        	}//막대 형식 데이터셋의 범례를 그린 후 라인 형식 데이터셋의 범례를 그림.
    	} else if(chart.config.type == 'line'){//라인 차트일 경우
    		for (i = 0; i <chart.data.datasets.length; i++) {
        		if(!(chart.data.datasets[i].hideLegend) && chart.data.datasets[i].label){
        			text.push('<li datasetIndex="'+i+'"><span class="line" style="background-color:' + chart.data.datasets[i].borderColor + '"></span>');
        			text.push('<span>'+chart.data.datasets[i].label+'</span>');
        			text.push('</li>');
        		} 
    		}
    	}
      	text.push('</ul>');
      	return text.join("");
    }
</script>

<div id="chartArea" style="width:700px;">  
	<div id="chartLegend" class="chartjs-legend"></div>
	<canvas id="chart"></canvas>
</div>

 

그러나 이것만 해서는.. 기본 범례에서 제공하는 범례를 클릭하면 

해당 데이터셋의 숨김/보이기 토글이 작동하지 않아 다소 불편했다.

그래서 나는 사용자 범례에 해당 기능도 추가했었다.

 

다음 글에서 설명하도록 하겠다.

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

chart.js에서 그래프 위에 값 그리는 법도 역시 Chart.plugins.register를 확장해서 아래와 같이 사용한다.

<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">
Chart.plugins.register({
  afterDraw: function (chart, easing) {
    if (chart.config.options.showValue) {
        var ctx = chart.chart.ctx;
        var fontSize = chart.config.options.showValue.fontSize || "9";
        var fontStyle = chart.config.options.showValue.fontStyle || "Arial";
        ctx.font =  fontSize + "px " + fontStyle;
        ctx.textAlign = chart.config.options.showValue.textAlign || "center";
        ctx.textBaseline = chart.config.options.showValue.textAlign || "bottom";
	
        chart.config.data.datasets.forEach(function (dataset, i) {
            ctx.fillStyle = dataset.fontColor || chart.config.options.showValue.textColor || "#000";
            dataset.data.forEach(function (data, j) {
               if(dataset.hideValue != true){
                	var txt = Math.round(data*100)/100;
                	var xCoordinate = dataset._meta[chart.id].data[j]._model.x;
                	var yCoordinate = dataset._meta[chart.id].data[j]._model.y;
                	var yCoordinateResult;

                	if(dataset.type == 'line'){
                		yCoordinateResult = yCoordinate + 21 > chart.scales[chart.options.scales.xAxes[0].id].top ? chart.scales[chart.options.scales.xAxes[0].id].top :  yCoordinate + 21;
                	} else{
                		yCoordinateResult = yCoordinate - 10;
                	}
                	ctx.fillText(txt, xCoordinate, yCoordinateResult);
                }
             });
          });
        }
      }
    }
});

var barChartData = {
        labels: ["label1", "label2", "label3", "label4"],
        datasets: [{
            label: 'Dataset 1',
            backgroundColor: ["rgba(220,220,220,0.5)", "navy", "red", "orange"],
            data: [
                Math.random(),
                Math.random(),
                Math.random(),
                Math.random()
            ]
      }]
};
	
window.onload = function() {
	var ctx5 = $('#chart5').get(0).getContext("2d");
	window.theChart5 = new Chart(ctx5, {
            type: 'bar',
            data: barChartData,
            options: {
                responsive: true,
                legend: {
                	display: false
                },
                scales: {
                	xAxes: [{
                		  gridLines: {
                		    display: false
                		  },
                		}],
	                yAxes: [{
	                	gridLines: {
                		    drawBorder: false//축과 데이터의 경계선 표시 여부
                		  },
	                    ticks: {
	                    	display: false,//축의 값 표시 여부
	                        max: 1,
	                        min: 0
	                    }
	                  }]
                },
                animation:false,
                showValue:{
                fontStyle: 'Helvetica', //Default Arial
                fontSize: 20
	     }
       }
 });
</script>
<div>
	<canvas id="chart5"></canvas>
</div>

 

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

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. 30. 14:29

ionic2, Angular에서 Chart.js 사용법2 개발/Chart.js2017. 11. 30. 14:29

반응형

 

그냥 오리지널 Chart.js를 ionic2에서도 사용할 수 있는 방법이 없는 줄 알았는데.. 있었다.

이 방법이 더 웹에서 사용하던 Chart.js 방법과 유사하기 때문에

앞으로 나는 이 방법을 더 쓰게 될 것 같다.

 

사용 방법은 다음과 같다.

 

1. npm을 사용하여 chart.js를 설치한다.

$ npm  install chart.js --save

 

2. html 파일을 작성한다.

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
   <ion-card>
      <ion-card-content>
        <canvas #chartCanvas></canvas>
      </ion-card-content>
   </ion-card>
</ion-content>

 

3. ts 파일을 작성한다.

import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Chart } from 'chart.js';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild('chartCanvas') chartCanvas;
  chart: any;
  ionViewDidLoad() {
        this.chart = new Chart(this.chartCanvas.nativeElement, {
            type: 'bar',
            data: {
                labels: ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"],
                datasets: [{
                    label: '# of Votes',
                    data: [
                        Math.random(),
                        Math.random(), 
                        Math.random(), 
                        Math.random(), 
                        Math.random(), 
                        Math.random()
                      ],
                    backgroundColor: [
                        'Red',
                        '#FFA500',
                        '#FFFF00',
                        'rgba(50, 205, 50, 1)',
                        'Blue',
                        'rgb(128, 0, 128)'
                    ]
                }]
            },
            options: {

            }
        });
  }
}

 

- web과 다른 점은 canvas의 context를 $('#chartCanvas').get(0).getContext("2d")가 아닌 this.chartCanvas.nativeElement로 가져온다는 것이다.

- 색깔은 보다시피 여러 가지 방법으로 정할 수 있다. 원하는 방법으로 쓰면 될 듯.

 

4. run을 하면 다음과 같은 차트가 그려진 것을 볼 수 있다.

$ cordova run android

 

 

 

 

출처 : https://www.joshmorony.com/adding-responsive-charts-graphs-to-ionic-2-applications/

반응형
:
Posted by 리샤씨


반응형
반응형