2 min read

chart js examples

Chart.js test

Examples from: http://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/

// Bar chart
new Chart(document.getElementById("bar-chart"), {
    type: 'bar',
    data: {
      labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
      datasets: [
        {
          label: "Population (millions)",
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
          data: [2478,5267,734,784,433]
        }
      ]
    },
    options: {
      legend: { display: false },
      title: {
        display: true,
        text: 'Predicted world population (millions) in 2050'
      }
    }
});

Iris Data Set

Let’s try to make it interactive

library(tidyverse)
library(jsonlite)
send_df_to_js <- function(df){
  cat(
    paste(
    '<script>
      var data = ',toJSON(df),';
    </script>'
    , sep="")
  )
}
data("iris")

data <- iris %>% group_by(Species) %>% summarise(PetalWidthAvg = mean(Petal.Width))

send_df_to_js(data)
// Bar chart
var labelsInput = data.map(function(e) {
   return e.Species;
});


var dataInput = data.map(function(e) {
   return e.PetalWidthAvg;
});

var colorInput = ["red", "blue", "green", "orange"];
var i = 0;

new Chart(document.getElementById("bar-chart2"), {
    type: 'bar',
    data: {
      labels: labelsInput,
      datasets: [
        {
          label: "Average Petal Width",
          backgroundColor: colorInput[i],
          data: dataInput
        }
      ]
    },
    options: {
      legend: { display: false },
      title: {
        display: true,
        text: 'Iris Test'
      }
    }
});

function outcome(i) {
    



new Chart(document.getElementById("bar-chart2"), {
    type: 'bar',
    data: {
      labels: labelsInput,
      datasets: [
        {
          label: "Average Petal Width",
          backgroundColor: colorInput[i],
          data: dataInput
        }
      ]
    },
    options: {
      legend: { display: false },
      title: {
        display: true,
        text: 'Iris Test'
      }
    }
});












};