has2k1 / plotnine

A Grammar of Graphics for Python
https://plotnine.org
MIT License
3.89k stars 209 forks source link

(dodged) Bars overlap axis when using 2x`geom_bar()` and `geom_text` #798

Closed mcanouil closed 3 weeks ago

mcanouil commented 4 weeks ago

Take the code below:

from plotnine import *
import polars as pl

(
    ggplot(
        data=pl.DataFrame(
            {
                "X": ["x", "x", "y", "y"],
                "GROUP": ["A", "B", "A", "B"],
                "COUNT": [42, 24, 32, 18],
                "TOTAL": [74, 74, 50, 50],
            }
        )
    ) +
        aes(x="X", y="COUNT") +
        scale_y_continuous(expand=(0, 0, 0.05, 0)) +
        scale_x_discrete(expand=(0, 0, 0.05, 0)) +
        theme(axis_line=element_line()) +
        geom_bar(stat="identity") +
        geom_text(mapping=aes(label="TOTAL", y="TOTAL+1")) +
        geom_bar(mapping=aes(fill="GROUP"), position="dodge", stat="identity")
)

See how the dodged bars from the last geom overlaps both x/y-axis?

image

Now, if you remove one of the geom_ (any), there are no issues, e.g., removing geom_text:

image

has2k1 commented 3 weeks ago

matplotlib sets a very low zorder=2.5 for the axis line (spline). We need to override it.

Actually, this theme(axis_line=element_line(zorder=100)) works, but we will set our own default.