Chart Js

Ver Ejemplo en CodePen

Implementacion Html

Ejemplo

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./style.css">
    <meta name="viewport" content="width=device-width, user-scalable=1, initial-scale=1">

    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
    
</head>
<body>
    <div class="line-chart">
        <div class="aspect-ratio">
          <canvas id="chart"></canvas>
        </div>
      </div>

      <div class="circle-chart">
        <div class="aspect-ratio">
          <canvas id="ctx"></canvas>
        </div>
      </div>
      <script type="text/javascript" src="./chartScript.js"></script>
</body>
</html>

Script ejemplo

grafico linear

Crear archivo script, segun ejemplo: “chartScript.js”, o crear un tag html con el siguiente contenido al final del tag .

// ============================================
// para version Chart.js v2.5.0
// http://www.chartjs.org/docs
// ============================================

var chart = document.getElementById("chart").getContext("2d"),
	gradient = chart.createLinearGradient(0, 0, 0, 450);
gradient.addColorStop(0, "rgba(255, 0,0, 0.5)");
gradient.addColorStop(0.5, "rgba(255, 0, 0, 0.25)");
gradient.addColorStop(1, "rgba(255, 0, 0, 0)");

var data = {
	labels: [
		"Jan",
		"Feb",
		"Mar",
		"Apr",
		"May",
		"Jun",
		"Jul",
		"Aug",
		"Sep",
		"Oct",
		"Nov",
		"Dec"
	],
	datasets: [
		{
			label: "Stock A",
			fill: true,
			lineTension: 0.1,
			backgroundColor: "rgba(0,0,0,0)",
			borderColor: "blue", // The main line color
			borderCapStyle: "square",
			borderDash: [], // try [5, 15] for instance
			borderDashOffset: 0.0,
			borderJoinStyle: "miter",
			pointBorderColor: "black",
			pointBackgroundColor: "white",
			pointBorderWidth: 1,
			pointHoverRadius: 8,
			pointHoverBackgroundColor: "white",
			pointHoverBorderColor: "blue",
			pointHoverBorderWidth: 2,
			pointRadius: 4,
			pointHitRadius: 10,
			// notice the gap in the data and the spanGaps: true
			data: [65, 59, 80, 81, 56, 55, 40, 39, 60, 55, 30, 78],
			spanGaps: true
		},
		{
			label: "Stock B",
			fill: true,
			lineTension: 0.1,
			backgroundColor: "rgba(167,105,0,0.4)",
			borderColor: "red",
			borderCapStyle: "butt",
			borderDash: [],
			borderDashOffset: 0.0,
			borderJoinStyle: "round",
			pointBorderColor: "black",
			pointBackgroundColor: "white",
			pointBorderWidth: 1,
			pointHoverRadius: 8,
			pointHoverBackgroundColor: "brown",
			pointHoverBorderColor: "yellow",
			pointHoverBorderWidth: 2,
			pointRadius: 4,
			pointHitRadius: 10,
			backgroundColor: "rgba(255, 255, 255, 0)",
			// notice the gap in the data and the spanGaps: false
			data: [10, 20, 60, 95, 64, 78, 90, 24, 70, 40, 70, 89],
			spanGaps: false
		}
	]
};

var options = {
	responsive: true,
	maintainAspectRatio: true,
	animation: {
		easing: "easeInOutQuad",
		duration: 520
	},
	scales: {
		xAxes: [
			{
				gridLines: {
					color: "rgba(290, 0, 200, 0.05)",
					lineWidth: 1
				}
			}
		],
		yAxes: [
			{
				gridLines: {
					color: "rgba(200, 200, 200, 0.08)",
					lineWidth: 1
				}
			}
		]
	},
	elements: {
		line: {
			tension: 1
		}
	},
	legend: {
		display: false
	},
	point: {
		backgroundColor: "white"
	},
	tooltips: {
		titleFontFamily: "Open Sans",
		backgroundColor: "rgba(0,0,0,0.3)",
		titleFontColor: "blue",
		caretSize: 9,
		cornerRadius: 2,
		xPadding: 10,
		yPadding: 10
	}
};

var chartInstance = new Chart(chart, {
	type: "line",
	data: data,
	options: options
});

grafico circular


ctx = document.getElementById('ctx').getContext('2d');
chart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        segmentStrokeWidth: 20,
        segmentStrokeColor: "rgba(255, 255, 6, 0.4)",
        datasets: [{
            label: 'Colors',
            data: [9, 8, 7, 6, 5, 4, 3, 2, 1],
            backgroundColor: ['rgba(255, 99, 132, 0.2)', "#FF4136",
             'rgba(255, 99, 22, 0.5)', "#FF851B", "#7FDBFF", "#B10DC9",
             'rgba(255, 99, 132, 0.9)','rgba(255, 99, 132, 0.7)',
             'rgba(255, 99, 132, 0.5)']
        }],
        labels: ['a','b','c','d','e','f','g','h','i']
    },
    options: {
        responsive: true,
        title:{
            display: true,
            text: "Color test"
        }
    }
});


Labels

Los label en grafico circular pueden ser removidos quitando la propiedad “labels” del objeto data.

ctx = document.getElementById('ctx').getContext('2d');
chart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        segmentStrokeWidth: 20,
        segmentStrokeColor: "rgba(255, 255, 6, 0.4)",
        datasets: [{
            label: 'Colors',
            data: [9, 8, 7, 6, 5, 4, 3, 2, 1],
            backgroundColor: ['rgba(255, 99, 132, 0.2)', "#FF4136", 'rgba(255, 99, 22, 0.5)', "#FF851B", "#7FDBFF", "#B10DC9",'rgba(255, 99, 132, 0.9)','rgba(255, 99, 132, 0.7)','rgba(255, 99, 132, 0.5)']
        }],
        labels: ['a','b','c','d','e','f','g','h','i']
    },

Animacion inicial en css

Como complemento visual es posible añadir animaciones al inicio de la carga del elemento.

:root {
--dark : rgba(5, 1, 44, 0.776);
}

*:before,
*:after {
  box-sizing: inherit;
}

.line-chart {
	animation: fadeIn 600ms cubic-bezier(.57,.25,.65,1) 1 forwards;
  opacity: 0;
	max-width: 640px;
	width: 100%;
}

.circle-chart {
	animation: fadeIn 600ms cubic-bezier(.57,.25,.65,1) 1 forwards;
  opacity: 0;
	max-width: 640px;
	width: 100%;
}

.aspect-ratio {
  height: 0;
  padding-bottom: 50%; // 495h / 990w
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

Implementacion Angular

Instalacion ChartJs

npm i --save chart.js@2.5.0

app.component.ts

Esto debe añadirse en el componente que contenga al grafico.

    import { Component } from '@angular/core';
    import * as Chart from 'chart.js'
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'angular8chartjs';
      canvas: any;
      canvas0: any;
      ctx: any;
      ctx0: any;
      gradient: any;

      ngAfterViewInit() {
        this.canvas = document.getElementById('myChart');
        this.canvas0 = document.getElementById('myChart0');
        this.ctx0 = this.canvas0.getContext('2d');
        this.ctx = this.canvas.getContext('2d');
        
        // la variable gradient es para crear los colores de fondo en
        // el grafico de lineas
        
        this.gradient = this.ctx.createLinearGradient(0, 0, 0, 450);
        this.gradient.addColorStop(0, 'rgba(255, 0,0, 0.7)');
        this.gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.25)');
        this.gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
        
        let myChart = new Chart(this.ctx, {
          type: 'line',
          data: {
              labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
              "Aug", "Sep", "Oct", "Nov", "Dec"], 
              datasets: [{
                  label: "Stock A",
                  fill: true,
                  lineTension: 0.1,
                  borderColor: "blue", // The main line color
                  borderCapStyle: 'square',
                  borderDash: [5,10], // try [5, 15] for instance
                  borderDashOffset: 0.0,
                  borderJoinStyle: 'miter',
                  pointBorderColor: "black",
                  pointBackgroundColor: "white",
                  pointBorderWidth: 1,
                  pointHoverRadius: 8,
                  pointHoverBackgroundColor: "white",
                  pointHoverBorderColor: "blue",
                  pointHoverBorderWidth: 2,
                  pointRadius: 4,
                  pointHitRadius: 10,
                  // vacio en la data y spanGaps: true
                  data: [65, 59, 80, 81, 56, 55, 40, ,60,55,30,78],
                  spanGaps: true,
                }, {
                  label: "Stock B",
                  fill: true,
                  lineTension: 0.1,
                  borderColor: "red",
                  borderCapStyle: 'butt',
                  borderDash: [],
                  borderDashOffset: 0.0,
                  borderJoinStyle: 'miter',
                  pointBorderColor: "white",
                  pointBackgroundColor: "white",
                  pointBorderWidth: 1,
                  pointHoverRadius: 8,
                  pointHoverBackgroundColor: "brown",
                  pointHoverBorderColor: "yellow",
                  pointHoverBorderWidth: 2,
                  pointRadius: 4,
                  pointHitRadius: 10,
                  backgroundColor: this.gradient,
                  // !en este data, hay saltos, que se veran en vacio 
                  // notese tambien el spanGaps: false
                  data: [10, 20, 60, 95, 64, 78, 90,,70,40,70,89],
                  spanGaps: false,
                }
            
              ]
           
          },
          options: {
            responsive: true,
            display:true,
            scales: {
              xAxes: [{
                gridLines: {
                  color: 'rgba(200, 0, 200, 0.05)',
                  lineWidth: 1
                }
              }],
              yAxes: [{
                gridLines: {
                  color: 'rgba(200, 200, 200, 0.08)',
                  lineWidth: 1
                }
              }]
            },
            elements: {
              line: {
                tension: 0.4
              }
            },
            legend: {
              display: false
            },
            point: {
              backgroundColor: 'white'
            },
            tooltips: {
              titleFontFamily: 'Open Sans' ,
              backgroundColor: 'rgba(0,0,0,0.3)',
              titleFontColor: 'black',
              caretSize: 5,
              cornerRadius: 2,
              xPadding: 10,
              yPadding: 10
            }
          }
        });
    
       let chart = new Chart(this.ctx0, {
          type: 'doughnut',
          data: {
              segmentStrokeColor: "rgba(255, 255, 6, 0.4)",
              datasets: [{
                  label: 'Colors',
                  data: [9, 8, 7, 6, 5, 4, 3, 2, 1],
                  backgroundColor: ['rgba(255, 99, 132, 0.2)', "#FF4136", 
                  'rgba(255, 99, 22, 0.5)', "#FF851B", "#7FDBFF", "#B10DC9",
                  'rgba(255, 99, 132, 0.9)','rgba(255, 99, 132, 0.7)',
                  'rgba(255, 99, 132, 0.5)']
              }],
              
          },
          options: {
              responsive: true,
              title:{
                  display: true,
                  text: "Color test"
              }
          }
      });
      }
    }

app.component.html

<canvas id="myChart"></canvas>
<canvas id="myChart0"></canvas> 

Responsividad

Por defecto en el objeto options de la configuracion del script para el grafico, puede establecerse la variable responsive como “true” para permitir al grafico autoajustarse a su contenedor o establecerlo como false para manejar la responsividad de forma externa con otra herramienta, (css).