Line With Changing Color

<h2>Alternating line color via data</h2> amCharts 4 brings a powerful concept - property fields, which allows binding any property of the Line series segment to values in data. Once a property, say a color, is overridden via data, the Line series remembers it and continues coloring subsequent segments in the same color. [amcharts2_button href="https://www.amcharts.com/docs/v4/concepts/data/#Property_fields"]More about property fields[/amcharts2_button]

by Rogério Saraceni

HTML

<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<div id="chartdiv"></div>

CSS

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

#chartdiv {
  width: 100%;
  height: 500px;
}

JavaScript

// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

var chart = am4core.create("chartdiv", am4charts.XYChart);

chart.paddingRight = 0;
chart.paddingLeft = 0;

var data = [];

chart.data = [{
  "year": "2014",
  "income": 23.5,
  "expenses": 21.1
}, {
  "year": "2015",
  "income": 26.2,
  "expenses": 30.5
}, {
  "year": "2020",
  "income": 34.1,
  "expenses": 31.9
}, {
  "year": "2021",
  "income": 34.1,
  "expenses": 31.9
},{
  "year": "2024",
  "income": 34.1,
  "expenses": 31.9
}];

var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.ticks.template.disabled = true;
categoryAxis.renderer.line.opacity = 0;
categoryAxis.renderer.grid.template.disabled = true;
categoryAxis.renderer.minGridDistance = 40;
categoryAxis.dataFields.category = "year";
categoryAxis.startLocation = 0.4;
categoryAxis.endLocation = 0.6;
categoryAxis.renderer.labels.template.disabled = true;


var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.tooltip.disabled = true;
valueAxis.renderer.line.opacity = 0;
valueAxis.renderer.ticks.template.disabled = true;
valueAxis.min = 0;
valueAxis.renderer.labels.template.disabled = true;

var lineSeries = chart.series.push(new am4charts.LineSeries());
lineSeries.dataFields.categoryX = "year";
lineSeries.dataFields.valueY = "income";
lineSeries.tooltipText = "income: {valueY.value}";
lineSeries.fillOpacity = 0.5;
lineSeries.strokeWidth = 3;
lineSeries.propertyFields.stroke = "lineColor";
lineSeries.propertyFields.fill = "lineColor";

var bullet = lineSeries.bullets.push(new am4charts.CircleBullet());
bullet.circle.radius = 6;
bullet.circle.fill = am4core.color("#fff");
bullet.circle.strokeWidth = 3;

chart.cursor = new am4charts.XYCursor();
chart.cursor.behavior = "panX";
chart.cursor.lineX.opacity = 0;
chart.cursor.lineY.opacity = 0;