Legend Justification Functions¶

Special theme functions for setting legend justification:

  • legendJustificationCenter() - the default behavior
  • legendJustificationTop()
  • legendJustificationRight()
  • legendJustificationBottom()
  • legendJustificationLeft().
In [1]:
%useLatestDescriptors
%use lets-plot
In [2]:
LetsPlot.getInfo()
Out[2]:
Lets-Plot Kotlin API v.4.12.0. Frontend: Notebook with dynamically loaded JS. Lets-Plot JS v.4.8.1.
Outputs: Web (HTML+JS), Kotlin Notebook (Swing), Static SVG (hidden)
In [3]:
val data = mapOf(
    "x" to listOf(0.0, 0.4, 1.0),
    "y" to listOf(0.0, 0.6, 1.0),
    "Color" to listOf("A", "B", "C")
)

val p =
    letsPlot(data) { x = "x"; y = "y"; color = "Color" } +
        geomPoint() +
        theme(plotTitle = elementText(hjust = 0.5)) +
        ggsize(500, 300)
In [4]:
// The base plot with the legend in the center

p + ggtitle("Default legend position")
Out[4]:
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 Default legend position y x Color A B C
In [5]:
// Align the legend to the top or bottom

gggrid(
    listOf(
        p + theme().legendJustificationTop() + ggtitle("Align legend to the top"),
        p + theme().legendJustificationBottom() + ggtitle("Align legend to the bottom")
    ),
    ncol = 2
)
Out[5]:
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 Align legend to the top y x Color A B C 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 Align legend to the bottom y x Color A B C
In [6]:
// When the legend is placed at the top or bottom, you can apply left or right justification

gggrid(
    listOf(
        p + theme()
            .legendPositionBottom()
            .legendJustificationLeft() 
        + ggtitle("Align legend to the left"),
        p + theme()
            .legendPositionBottom()
            .legendJustificationRight() 
        + ggtitle("Align legend to the right")
    ),
    ncol = 2
)
Out[6]:
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 Align legend to the left y x Color A B C 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 Align legend to the right y x Color A B C