%useLatestDescriptors
%use lets-plot
%use dataframe
val df = DataFrame.readCSV("https://raw.githubusercontent.com/JetBrains/lets-plot-kotlin/master/docs/examples/data/mpg.csv")
df.head()
DataFrame: rowsCount = 5, columnsCount = 12
untitled | manufacturer | model | displ | year | cyl | trans | drv | cty | hwy | fl | class |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | audi | a4 | 1.800000 | 1999 | 4 | auto(l5) | f | 18 | 29 | p | compact |
2 | audi | a4 | 1.800000 | 1999 | 4 | manual(m5) | f | 21 | 29 | p | compact |
3 | audi | a4 | 2.000000 | 2008 | 4 | manual(m6) | f | 20 | 31 | p | compact |
4 | audi | a4 | 2.000000 | 2008 | 4 | auto(av) | f | 21 | 30 | p | compact |
5 | audi | a4 | 2.800000 | 1999 | 6 | auto(l5) | f | 16 | 26 | p | compact |
val mpg = df.toMap()
// Default legend
val p1 = letsPlot(mpg) { x = "cty"; y = "hwy" } + geomPoint() { color = "cyl" }
p1
// Legend name
p1 + scaleColorContinuous(name = "Number of cylinders")
// Breaks and labels
p1 + scaleColorContinuous(breaks = listOf(4, 5, 6, 8), labels = listOf("four", "five", "six", "eight"))
// Format labels
p1 + scaleColorContinuous(format = "{} cylinders\nin the vehicle’s engine")
guideLegend()
¶// Default categorical legend
val p2 = letsPlot(mpg) { x = "displ"; y = "hwy"; color = "manufacturer" } + geomPoint(size = 5)
p2
// Legend name
p2 + scaleColorDiscrete(guide = guideLegend("Company"))
// Layout the legend in two columns
p2 + scaleColorDiscrete(guide = guideLegend(ncol = 2))
// Fill by rows
p2 + scaleColorDiscrete(guide = guideLegend(ncol = 2, byRow = true))
guideColorbar()
¶// Default color legend
val p3 = letsPlot(mpg) { x = "displ"; y = "hwy" } + geomPoint() { color = "cty" }
p3
// Legend name
p3 + scaleColorContinuous(guide = guideColorbar("City mileage"))
// Adjust colorbar size
p3 + scaleColorContinuous(guide = guideColorbar(barWidth = 10, barHeight = 200))
// Fewer bins
p3 + scaleColorContinuous(breaks = listOf(13, 22, 31), guide = guideColorbar(nbin = 3))
guides()
¶// Default complex legend
val p4 = letsPlot(mpg) { x = "displ"; y = "hwy" } + geomPoint(size = 5) { color = "cty"; shape = "drv" }
p4
// Guides for 'color' and 'shape' aesthetics
p4 + guides(color = guideColorbar(barWidth = 10), shape = guideLegend(ncol = 2))
p4 + guides(shape = guideLegend(size = 8, color = "#f03b20"))
// Draw legend below the plot area
p4 + theme().legendPositionBottom()
// Specify position, justification and orientation
p4 + theme().legendPosition(1, 1).legendJustification(1, 1).legendDirectionHorizontal()