%useLatestDescriptors
%use dataframe
%use lets-plot
import kotlinx.datetime.*
fun LocalDateTime.toMillis(): Long {
return toInstant(TimeZone.currentSystemDefault()).toEpochMilliseconds()
}
fun LocalDateTime.Companion.fromYear(year: Int): LocalDateTime {
return LocalDateTime(year, 1, 1, 0, 0)
}
fun DataFrame<*>.parseDates(column: String): DataFrame<*> {
return this.convert(column).toLocalDateTime()
.convert(column).with { (it as LocalDateTime).toMillis() }
}
fun millisByYear(year: Int): Long {
return LocalDateTime.fromYear(year).toMillis()
}
val presidentialDf = DataFrame.readCSV("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/presidential.csv")
.parseDates("start").parseDates("end")
val economicsDf = DataFrame.readCSV("https://vincentarelbundock.github.io/Rdatasets/csv/ggplot2/economics.csv")
.parseDates("date")
val breaks = listOf(2.5, 5.0, 10.0)
letsPlot() +
geomBand(data = presidentialDf.toMap(), size = 0, alpha = 0.4) { xmin = "start"; xmax = "end"; fill = "party" } +
geomLabel(data = presidentialDf.toMap(), y = 4_000, alpha = 0.6, angle = 90, vjust = 1, showLegend = false)
{ x = "start"; label = "name"; color = "party" } +
geomLine(data = economicsDf.toMap()) { x = "date"; y = "unemploy" } +
scaleXDateTime(name = "Year") +
scaleYContinuous("Unemployment (x\\(10^3\\))", trans = "log10",
breaks = breaks.map { it * 10.0.pow(3) },
labels = breaks.map { it.toString() }) +
scaleFillDiscrete(name = "") +
coordCartesian(xlim = Pair(millisByYear(1966), millisByYear(2016))) +
guides(fill = guideLegend(alpha = 0.4, color = "paper")) +
ggsize(1000, 400) +
ggtitle("Unemployment in the US", "1967 to 2015") +
theme(plotTitle = elementText(size = 18, face = "bold")).legendPositionTop()