Search code examples
pythonplotnine

Plotnine Wrap Text in Facet Wrap


I am plotting a faceted plot which has very long labels. I am translating some code from R to python. I am looking to wrap the text of the x-axis over multiple lines. I have shown the R code below.

The R code

q <- ggplot() + ...
q + scale_x_discrete(labels = function(x) str_wrap(x, width = 8)) 

Is there an equivalent for this using plotnine?


Solution

  • You could do that by using textwrap and a custom labeler function.

    See here for examples from Plotnine team on date/time labels.

    Change the numeric argument (the second one in the function call) to increase/decrease the characters in the wrap.

    Example using mpg data:

    import pandas as pd
    import numpy as np
    
    from plotnine import *
    from plotnine.data import *
    
    %matplotlib inline
    
    # import textwrap and define the custom function
    import textwrap
    
    def wraping_func(text):
        return [textwrap.fill(wraped_text, 5) for wraped_text in text]
    
    # example usage
    
    (
        ggplot(mpg) 
        + geom_bar(aes(x='class'))
        + scale_x_discrete(breaks=mpg['class'].unique().tolist(), labels=wraping_func)
    )
    

    The output that will give the bar chart but labels are wrapt at the 5th character:

    the output that will give the bar chart but labels are wrapt at the 5th character