import io.data2viz.charts.*
import io.data2viz.charts.core.Padding
import io.data2viz.charts.core.*
import io.data2viz.charts.dimension.*
import io.data2viz.charts.chart.*
import io.data2viz.charts.chart.mark.*
import io.data2viz.charts.layout.*
import io.data2viz.charts.config.configs.*
import io.data2viz.charts.config.*
import io.data2viz.charts.core.CursorType
import io.data2viz.math.*
import io.data2viz.color.*
import io.data2viz.geom.*
import io.data2viz.shape.Symbols
import io.data2viz.dsv.Dsv
import io.data2viz.viz.*
import org.w3c.fetch.Response
import kotlinx.browser.window
import kotlin.js.Promise
import kotlinx.datetime.Instant
val width = 450.0
val height = 300.0
private val city = "San Diego"
private val year = 2016
data class Weather(
val city: String,
val year: Int,
val month: Int,
val highTemp: Double,
val avgTemp: Double,
val lowTemp: Double,
val precip: Double)
private fun parseWeather(row: List<String>) = Weather(
row[0],
row[1].toInt(),
row[2].toInt(),
row[3].toDouble(),
row[4].toDouble(),
row[5].toDouble(),
row[6].toDouble()
)
private val months = listOf("Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec.")
fun main() {
// Creating and sizing the VizContainer
val vc0 = newVizContainer().apply { size = Size(width, height) }
val vc1 = newVizContainer().apply { size = Size(width, height) }
val vc2 = newVizContainer().apply { size = Size(width, height) }
val request: Promise<Response> =
window.fetch("https://docs.google.com/spreadsheets/d/e/2PACX-1vTX4QuCNyDvUoAwk6Jl6UJ4r336A87VIKQ5BVyEgowXG_raXdFBMvmUhmz1LLc07GavyC9J6pZ4YHqJ/pub?gid=650761999&single=true&output=csv")
request.then {
it.text().then {
val results = Dsv()
.parseRows(it)
.drop(1)
.map { parseWeather(it) }
.filter { it.city == city }
.filter { it.year == year }
vc0.createChart(results)
vc1.createChart(results, greenConfig)
vc2.createChart(results, lightConfig)
}
}
}
private fun VizContainer.createChart(results: List<Weather>, config: ChartConfig = configuration {}) {
chart(results, config) {
title = "Avg. temperature and precipitation, $city"
config {
cursor {
show = true
type = CursorType.Vertical
}
title {
fontSize = 14.0
}
}
val monthDim = discrete( { domain.month } ) {
formatter = { "${months[this - 1]} "}
}
val tempDim = quantitative( { domain.avgTemp } ) {
name = "Average temperature for the month"
formatter = { "$this°F" }
}
val precipDim = quantitative( { domain.precip } ) {
name = "Total precipitations for the month"
formatter = { "$this\"" }
}
bar(monthDim, precipDim) {
val color = config.mark.fills[0].darken(2.0)
y {
end = 5.0
layoutPosition = LayoutPosition.Right
fontColor = color
strokeColor = color
tickStroke = color
}
}
line(monthDim, tempDim) {
val color = config.mark.strokeColors[0]
showMarkers = true
strokeWidth = constant(2.0)
y {
fontColor = color
strokeColor = color
tickStroke = color
fontWeight = FontWeight.BOLD
start = .0
end = 100.0
}
}
}
}
comments