Search code examples
pythonplotnine

Plotnine legend justified to left


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?


Solution

  • 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.