Chartjs Line Color Between Two Points

余生长醉 提交于 2020-06-25 21:37:41

问题


Is there any way to set line color of specific sections in between two points in chart.js?

I would like to color the section 00-07 gray, 07-15 red, and 15-23 blue.

Here is what I am passing as the data attribute in the options object to initialize the chart:

var chartData = {
labels: [/* a single dimensional array of strings */],
datasets: [
    {
        label: '',
        data: [/* a single dimensional array of totals */],
        fill: false,
        backgroundColor: '#e7eaeb',
        borderColor: red
    }
  ]
};

I think this is where I need to add the graph section points and colors, but I do not know how.


回答1:


HI Michael Hurley I think you should use:

interpolation: http://www.chartjs.org/samples/latest/charts/line/interpolation-modes.html

or

Multi-axis: http://www.chartjs.org/samples/latest/charts/line/multi-axis.html

My idea is we have 3 datasets with multi-color, End of dataset1 is first of dataset2.

Here my Example:

window.chartColors = { 	red: 'rgb(255, 99, 132)', 	orange: 'rgb(255, 159, 64)', 	yellow: 'rgb(255, 205, 86)', 	green: 'rgb(75, 192, 192)', 	blue: 'rgb(54, 162, 235)', 	purple: 'rgb(153, 102, 255)', 	grey: 'rgb(201, 203, 207)' }; 

var randomScalingFactor = function() {
			return Math.round(Math.random() * 100);
		};

		var config = {
			type: 'line',
			data: {
				labels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
				datasets: [{
					label: 'Cubic interpolation (monotone)',
					data: [0, 20, 20, 60, 60, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN],
					borderColor: window.chartColors.red,
					backgroundColor: 'rgba(0, 0, 0, 0)',
					fill: false,
					cubicInterpolationMode: 'monotone'
				}, {
					label: 'Cubic interpolation (default)',
					data: [NaN, NaN, NaN, NaN, 60, 120, 140, 180, 120, NaN, NaN, NaN, NaN],
					borderColor: window.chartColors.blue,
					backgroundColor: 'rgba(0, 0, 0, 0)',
					fill: false,
				}, {
					label: 'Linear interpolation',
					data: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 120, 125, 105, 110, 170],
					borderColor: window.chartColors.green,
					backgroundColor: 'rgba(0, 0, 0, 0)',
					fill: false,
					lineTension: 0
				}]
			},
			options: {
				responsive: true,
				title: {
					display: true,
					text: 'Chart.js Line Chart - Cubic interpolation mode'
				},
				tooltips: {
					mode: 'index'
				},
				scales: {
					xAxes: [{
						display: true,
						scaleLabel: {
							display: true
						}
					}],
					yAxes: [{
						display: true,
						scaleLabel: {
							display: true,
							labelString: 'Value'
						},
						ticks: {
							suggestedMin: -10,
							suggestedMax: 200,
						}
					}]
				}
			}
		};

	
			var ctx = document.getElementById('canvas').getContext('2d');
			window.myLine = new Chart(ctx, config);
canvas {
		-moz-user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
	}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:75%;">
		<canvas id="canvas"></canvas>
	</div>



回答2:


The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterLayout hook to create a linear gradient through CanvasRenderingContext2D.createLinearGradient().

In the following example, the linear gradient is created from the colors defined in data.dataset.colors.

new Chart('myChart', {
  type: 'line',
  plugins: [{
    afterLayout: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var gradientStroke = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
      var dataset = chart.data.datasets[0];
      dataset.colors.forEach((c, i) => {
        var stop = 1 / (dataset.colors.length - 1) * i;
        gradientStroke.addColorStop(stop, dataset.colors[i]);
      });
      dataset.backgroundColor = gradientStroke;
      dataset.borderColor = gradientStroke;
      dataset.pointBorderColor = gradientStroke;
      dataset.pointBackgroundColor = gradientStroke;
      dataset.pointHoverBorderColor = gradientStroke;
      dataset.pointHoverBackgroundColor = gradientStroke;
    }
  }],
  data: {
    labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    datasets: [{
      label: 'My Dataset',
      data: [101, 122, 103, 115, 95, 94, 100, 108, 112, 115, 119, 120, 109, 108, 105, 116, 117, 108, 109, 114],
      fill: false,
      colors: ['gray', 'gray', 'gray', 'gray','gray', 'gray', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue']
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          min: 0
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="70"></canvas>


来源:https://stackoverflow.com/questions/52120036/chartjs-line-color-between-two-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!