breakWidth Parameter in Datetime Scales¶

In datetime scales, the breakWidth parameter accepts a string specifying the interval between breaks, e.g., "2 weeks", "3 months", "12 hours".

In [1]:
%useLatestDescriptors
%use lets-plot
In [2]:
val csvUrl = "https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/economics.csv"
val text = java.net.URL(csvUrl).readText()
val lines = text.trim().split("\n")
val header = lines[0].split(",")
val dateIdx = header.indexOfFirst { it.trim('"') == "date" }
val unemployIdx = header.indexOfFirst { it.trim('"') == "unemploy" }

val start = java.time.LocalDate.of(2007, 1, 1)
val end = java.time.LocalDate.of(2013, 1, 1)

val dates = mutableListOf<Long>()
val unemploy = mutableListOf<Double>()

for (line in lines.drop(1)) {
    val cols = line.split(",")
    val dateStr = cols.getOrNull(dateIdx)?.trim()?.trim('"') ?: continue
    val date = runCatching { java.time.LocalDate.parse(dateStr) }.getOrNull() ?: continue
    if (!date.isBefore(start) && date.isBefore(end)) {
        val epochMs = date.atStartOfDay(java.time.ZoneOffset.UTC).toInstant().toEpochMilli()
        dates.add(epochMs)
        unemploy.add(cols[unemployIdx].trim().toDouble())
    }
}

val economics = mapOf("date" to dates, "unemploy" to unemploy)
println("Loaded ${dates.size} rows")
Loaded 72 rows
In [3]:
// A datetime scale with auto-selected breaks
letsPlot(economics) { x = "date"; y = "unemploy" } +
    geomLine(size = 5, alpha = 0.5, color = "teal") +
    scaleXDateTime() +
    themeClassic() +
    ggsize(800, 300)
Out[3]:
2007 2008 2009 2010 2011 2012 2013 8,000 10,000 12,000 14,000 unemploy date
In [4]:
letsPlot(economics) { x = "date"; y = "unemploy" } +
    geomLine(size = 5, alpha = 0.5, color = "teal") +
    scaleXDateTime(
        breakWidth = "3 months",      // breaks every 3 months
        format = "%b '%y"
    ) +
    themeClassic() +
    ggsize(800, 300)
Out[4]:
Dec '06 Mar '07 Jun '07 Sep '07 Dec '07 Mar '08 Jun '08 Sep '08 Dec '08 Mar '09 Jun '09 Sep '09 Dec '09 Mar '10 Jun '10 Sep '10 Dec '10 Mar '11 Jun '11 Sep '11 Dec '11 Mar '12 Jun '12 Sep '12 Dec '12 Mar '13 8,000 10,000 12,000 14,000 unemploy date