1

I want to change the facet title in plotnine (python ggplot) when 2 variables are used in faceting WITHOUT changing the data itself.

Example: using mpg data

 pretty = p9.ggplot(data=mpg, mapping = p9.aes(x='hwy', y='displ'))+ p9.geom_point(alpha = 0.6)
 pretty + p9.facet_grid("cyl~year")

I have the following plot:

enter image description here

I want to change the year to "yr 1999" and "yr 2008" and the cly titles to "c4", "c5","c6", "c8". But when I used the labeller in facet_grid:

  pretty + p9.facet_grid("cyl~year", labeller = ["c4", "c5","c6", "c8", "yr 1999", "yr 2008"])

the plot is not changed. I have tried to google around but did not find answer for changing faceting titles with two variables.

lll
  • 1,049
  • 2
  • 13
  • 39

1 Answers1

1

See the documentation for the labeller function.

import plotnine as p9
from plotnine.data import mpg

def col_func(s):
    return 'yr ' + s

pretty = p9.ggplot(data=mpg, mapping = p9.aes(x='hwy', y='displ'))+ p9.geom_point(alpha = 0.6)
pretty + p9.facet_grid("cyl~year", labeller=p9.labeller(cols=col_func))

enter image description here

has2k1
  • 2,095
  • 18
  • 16
  • thanks! i am just curious if i want to change the column name differently for each column, how should i do? for example, if i want to change it to "year 1999" and "yr 2008". I tried col_name = ["year 1999", 'yr 2008'] and call the labeller as labeller=p9.labeller(cols=col_name) but it does not work – lll Feb 08 '20 at 22:43
  • Use the function and put the selection code in there. e.g `def col_func(s): return {'1999': 'yr 2009', '2008': 'year 2008'}[s]` – has2k1 Feb 09 '20 at 17:37