How to change bar-color on a chart.js bar graph

I have a bar chart using chart.js. I want to be able to change the color of the bar-chart (the value part).

I’ve tried looking on the chart.js docs but I couldn’t find anything.

    <main>
        <div class="content">
            <h1>Results</h1>
            <h2>Trial 1</h2>
            <div class="results" class="results" id="trial-1"> <canvas class="show-results"></canvas></div>
            <h2>Trial 2</h2>
            <div class="results" id="trial-1"> <canvas class="show-results"></canvas></div>
            <h2>Trial 3</h2>
            <div class="results" id="trial-1"> <canvas class="show-results"></canvas></div>
            <h2>Trial 4</h2>
            <div class="results" id="trial-1"> <canvas class="show-results"></canvas></div>
            <h2>Trial 5</h2>
            <div class="results" id="trial-1"> <canvas class="show-results"></canvas></div>
            <h2>Results Overall</h2>
            <div class="results" id="trial-1"> <canvas class="show-results"></canvas></div>
        </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        const ctx = document.getElementsByClassName("show-results");
      for (let i = 0; i < ctx.length; i++) {
        new Chart(ctx[i], {
          type: 'bar',
          data: {
            labels: ['Lua', 'Python', 'JavaScript', 'Java', 'C', 'C++', 'F#', 'Haskell', 'C#', 'Rust', 'Go'],
            datasets: [{
              label: 'Time to compile and run',
              data: [12, 19, 3, 5, 2, 3],
              borderWidth: 1
            }]
          },
          options: {
            scales: {
              y: {
                beginAtZero: true
              }
            }
          }
        });
    }
      </script>

>Solution :

Simpy add

                'rgba(239, 197, 45, 1)'
            ]

To the datasets array in your code.

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        const ctx = document.getElementsByClassName("show-results");
      for (let i = 0; i < ctx.length; i++) {
        new Chart(ctx[i], {
          type: 'bar',
          data: {
            labels: ['Lua', 'Python', 'JavaScript', 'Java', 'C', 'C++', 'F#', 'Haskell', 'C#', 'Rust', 'Go'],
            datasets: [{
              label: 'Time to compile and run',
              data: [12, 19, 3, 5, 2, 3],
              borderWidth: 1,
              backgroundColor: [
                'rgba(239, 197, 45, 1)'
            ]
            }]
          },
          options: {
            scales: {
              y: {
                beginAtZero: true
              }
            }
          }
        });
    }
      </script>

Leave a Reply