class plotnine.aes(*args, **kwargs)[source]

Create aesthetic mappings

xexpression | array_like | scalar

x aesthetic mapping

yexpression | array_like | scalar

y aesthetic mapping


Other aesthetic mappings


Only the x and y aesthetic mappings can be specified as positional arguments. All the rest must be keyword arguments.

The value of each mapping must be one of:

  • string:

    import pandas as pd
    import numpy as np
    arr = [11, 12, 13]
    df = pd.DataFrame({'alpha': [1, 2, 3],
                       'beta': [1, 2, 3],
                       'gam ma': [1, 2, 3]})
    # Refer to a column in a dataframe
    ggplot(df, aes(x='alpha', y='beta'))
  • array_like:

    # A variable
    ggplot(df, aes(x='alpha', y=arr))
    # or an inplace list
    ggplot(df, aes(x='alpha', y=[4, 5, 6]))
  • scalar:

    # A scalar value/variable
    ggplot(df, aes(x='alpha', y=4))
    # The above statement is equivalent to
    ggplot(df, aes(x='alpha', y=[4, 4, 4]))
  • String expression:

    ggplot(df, aes(x='alpha', y='2*beta'))
    ggplot(df, aes(x='alpha', y='np.sin(beta)'))
    ggplot(df, aes(x='df.index', y='beta'))
    # If `count` is an aesthetic calculated by a stat
    ggplot(df, aes(x='alpha', y='stat(count)'))
    ggplot(df, aes(x='alpha', y='stat(count/np.max(count))'))

    The strings in the expression can refer to;

    1. columns in the dataframe

    2. variables in the namespace

    3. aesthetic values (columns) calculated by the stat

    with the column names having precedence over the variables. For expressions, columns in the dataframe that are mapped to must have names that would be valid python variable names.

    This is okay:

    # 'gam ma' is a column in the dataframe
    ggplot(df, aes(x='df.index', y='gam ma'))

    While this is not:

    # 'gam ma' is a column in the dataframe, but not
    # valid python variable name
    ggplot(df, aes(x='df.index', y='np.sin(gam ma)'))

aes has 2 internal methods you can use to transform variables being mapped.

  1. factor - This function turns the variable into a factor.

    It is just an alias to pd.Caterogical:

    ggplot(mtcars, aes(x='factor(cyl)')) + geom_bar()
  2. reorder - This function changes the order of first variable

    based on values of the second variable:

    df = pd.DataFrame({
        'x': ['b', 'd', 'c', 'a'],
        'y': [1, 2, 3, 4]
    ggplot(df, aes('reorder(x, y)', 'y')) + geom_col()

The group aesthetic

group is a special aesthetic that the user can map to. It is used to group the plotted items. If not specified, it is automatically computed and in most cases the computed groups are sufficient. However, there may be cases were it is handy to map to it.