has2k1 / plotnine

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

geom_col: overlapping x-axis labels when using `element_text(angle=45)` #863

Open nick-youngblut opened 1 month ago

nick-youngblut commented 1 month ago

reprex:

import plotnine as pn
from plotnine.data import mtcars

pn.ggplot(mtcars, pn.aes("name", "mpg")) \
    + pn.geom_col() \
    + pn.theme(
        figure_size=(10,3),
        axis_text_x=pn.element_text(angle=45)
    ) 

The resulting x-axis labels are not correctly positioned:

Screenshot 2024-08-05 at 10 47 12 AM

Using pn.element_text(angle=45, hjust=1) helps, but then the labels are too far to the left of each x-axis tick.

Another example from my own data:

Screenshot 2024-08-05 at 10 44 41 AM

The most relevant sections of my very long conda env:

# Name                    Version                   Build  Channel
python                    3.10.14         hd12c33a_0_cpython    conda-forge
plotnine                  0.13.6             pyhd8ed1ab_0    conda-forge
has2k1 commented 3 weeks ago

The text is rotated around the point at which it is aligned. By default that is the baseline/center. You need to change the alignment (va & ha), and also the rotation_mode which affects the order of rotation and alignment.

theme(
    axis_text_x=element_text(angle=45, va="top", ha="right", rotation_mode="anchor")
)
nick-youngblut commented 3 weeks ago

Thanks @has2k1 for the info! I didn't know that plotnine differed from the ggplot2 API in this regard. I'll keep that in mind.

has2k1 commented 3 weeks ago

Reopened so that it is documented.