Plotnine legend justified to left

46 Views Asked by At

I cannot justify the legend to the left despite adding legend_box_just="left". I'm using Plotnine version 0.13.0 with Python 3.11.

Code:

df = pd.DataFrame({
    'Date':  pd.date_range(start="2024-01-01", periods=11, freq="W").repeat(3),
    'Variable': ['A', 'B', 'C'] * 11,
    'Value': np.random.choice(range(50), 33)
})

plot = (ggplot(df, aes(x='Date', y='Value', fill='Variable'))
        + geom_bar(stat="identity")
        + labs(title="Title")
        + theme_minimal()
        + theme(
            legend_title=element_blank(),
            legend_direction="horizontal", legend_box="horizontal",
            legend_position="top", legend_box_just="left")
        )

plot.show()

Plot: enter image description here

How do I get the caption left justified and aligned with the title?

2

There are 2 best solutions below

2
has2k1 On BEST ANSWER

Use legend_justification=0 or legend_justification_top=0.

import pandas as pd
import numpy as np
from plotnine import *

df = pd.DataFrame({
    'Date':  pd.date_range(start="2024-01-01", periods=11, freq="W").repeat(3),
    'Variable': ['A', 'B', 'C'] * 11,
    'Value': np.random.choice(range(50), 33)
})

plot = (ggplot(df, aes(x='Date', y='Value', fill='Variable'))
        + geom_bar(stat="identity")
        + labs(title="Title")
        + theme_minimal()
        + theme(
            legend_justification=0,
            # legend_justification_top=0, # Alternatively, to be more specific
            legend_title=element_blank(),
            legend_direction="horizontal",
            legend_box="horizontal",
            legend_position="top",
            legend_box_just="left"
        )
    )

plot.show()

Justifying the legend with plotnine

This has revealed a bug i.e. the blanked legend title has been included in the justification. In the meantime you can use a negative justification factor. A fix will be out soon.

1
Nick ODell On

To put the legend in the upper-left hand corner, I'd suggest passing coordinates to legend_position.

Example:

plot = (ggplot(df, aes(x='Date', y='Value', fill='Variable'))
        + geom_bar(stat="identity")
        + labs(title="Title")
        + theme_minimal()
        + theme(
            legend_title=element_blank(),
            legend_direction="horizontal", legend_box="horizontal",
            legend_position=(0.2,0.9), legend_box_just="left")
        )

Plot:

example plot