In this second tutorial, you'll see some of the basic features of Charts-kt, and build a bar chart based on your data model.

This tutorial will help you understand how to:

  1. Parse and map a CSV file to a Kotlin data class
  2. Use your own model and data in your charts
  3. Describe your values through "dimensions"
  4. Create a bar chart
  5. Understand the "Datum" concept

What do you need?

Parsing a CSV file

This Google Spreadsheet CSV export contains statistical weather data for each month of 2016 and 2017, for 5 different cities.

Parsing this file is very easy using the multiplatform Dsv module of data2viz.

  1. create a Kotlin data class Weather to hold the information,
  2. load the file asynchronously using a Promise,
  3. parse each row and, if needed, drop the header (the first line of the file),
  4. finally, map each row of the file in a Weather instance.
//run highlight-only=true
import io.data2viz.dsv.Dsv
import kotlinx.browser.window
import kotlinx.html.div
import kotlinx.html.dom.append
import org.w3c.dom.Node
import org.w3c.fetch.Response
import kotlin.js.Promise

private val fileName =
    "<https://docs.google.com/spreadsheets/d/e/2PACX-1vTX4QuCNyDvUo>" +
            "Awk6Jl6UJ4r336A87VIKQ5BVyEgowXG_raXdFBMvmUhmz1LLc07Ga" +
            "vyC9J6pZ4YHqJ/pub?gid=650761999&single=true&output=csv"

fun Node.loadCSV() {
    val request: Promise<Response> = window.fetch(fileName)
    request.then { response ->
        response.text().then { csvContent ->
            val weatherData = parseWeatherCSV(csvContent)
            append {
                div {
                    +"Loaded ${weatherData.size} records"
                }
            }
        }
    }
}

data class Weather(
    val city: String,
    val year: Int,
    val month: Int,
    val highTemp: Double,
    val avgTemp: Double,
    val lowTemp: Double,
    val precipitation: Double
)

fun parseWeatherCSV(csvContent: String): List<Weather> = Dsv()
    .parseRows(csvContent)
    .drop(1)
    .map { row ->
        Weather(
            row[0],
            row[1].toInt(),
            row[2].toInt(),
            row[3].toDouble(),
            row[4].toDouble(),
            row[5].toDouble(),
            row[6].toDouble()
        )
    }

The Kotlin data class offers a very convenient way to hold your information loaded from your CSV file.