pythonpython-ggplotplotnine

How to map continuous variable to color in plotnine?


I'm trying to map a continuous variable to color in plotnine. In R, I can do this by setting color param to log(pop). In plotnine, I tried this alternative, and it generates this error:

ValueError: Image size of 300573x430 pixels is too large. It must be less than 2^16 in each direction.

from gapminder import gapminder
import math
p = ggplot(data=gapminder, mapping=aes(x='gdpPercap', y='lifeExp'))
(p + geom_point(mapping=aes(color=[math.log(v) for v in gapminder['pop']]))
   + scale_x_log10()
 )

Solution

  • Create an expression in a string. In that string you can refer to columns in the dataframe and variables in the environment. And it is simpler use vectorized functions from numpy rather than the math module.

    from gapminder import gapminder
    import numpy as np
    
    p = ggplot(data=gapminder, mapping=aes(x='gdpPercap', y='lifeExp'))
    (p + geom_point(mapping=aes(color='np.log(pop)'))
       + scale_x_log10()
     )