Plotnine Wrap Text in Facet Wrap
Asked Answered
B

1

7

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?

Bloodshot answered 25/1, 2021 at 19:44 Comment(0)
A
4

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

Augustineaugustinian answered 23/12, 2022 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.