Antimony
Antimony

Reputation: 39451

Set default line style in chart.js

Is there any way to set the default line style in chart.js to fill: false?

i.e. in the code below, I shouldn't have to write all the fill: false explicitly.

  type: 'line',

  data: {
    labels: data.months,
    datasets: [{
        fill: false,
        label: 'Gross',
        data: data.gross,
        backgroundColor: '#2f7ed8',
        borderColor: '#2f7ed8',
      }, {
        fill: false,
        label: 'Net',
        data: data.net,
        backgroundColor: '#8bbc21',
        borderColor: '#8bbc21',
      },
    ],
  },

The documentation says that you can set default options via Chart.defaults.global, but it is not clear to me whether and how you can change things like line style.

Upvotes: 0

Views: 1510

Answers (1)

Shiffty
Shiffty

Reputation: 2156

As you've already seen in the documentation you can set these settings with Chart.defaults.global. Which later get merged with the properties of the dataset.

Chart.defaults.global.elements.line.fill = false;

Settings like fill are found under Chart.defaults.global.elements. Logging the entire Chart.defaults.global object to the console, helps in finding the correct property to set.

Chart.defaults.global.elements.line.fill = false;

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: 'Dataset 1',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: 'Dataset 2',
        data: [6, 8, 4, 2, 4, 8],
        borderWidth: 1,
      },
      {
        label: 'Dataset 3 (filled)',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1,
        fill: true
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>

<canvas id="myChart" width="600" height="400"></canvas>

Upvotes: 2

Related Questions