Aes Function In R: Construct Aesthetic Mappings

aes function in r

Hi guys, today we will learn how to use the aes function in the R programming language together. So, please read this article to get more helpful information.

What is the ase function in R?

The aes function is a ggplot2 Aesthetic Mapping approach. Using this function, you can map data, features, or columns from your data set to the map. A plot’s visual aspects, or aesthetics, include lines, points, symbols, colors, location… anything that can be seen. You can, for example, map a column of your data to the x-axis of your plot or the y-axis.

The syntax of aes function

ase(x,y)

Parameters

  • x, y: The list of name-value pairs indicating which variables in the layer data should be mapped to which the matching Geom/stat employs aesthetics.

The example of aes function in R

In the following code example, you can understand this function better.

First, we will create an ase without the x and y names because the x and y are inferred.  

# Create an ase
aes(mpg/2, wt*2)

Or you can specify x, y if you need to calculation or to a constant.

# Map the functions of variables to the aesthetics
aes(x = mpg * 2, y = wt / cyl)

# The constants of variable
aes(x = 2, colour="smooth")

Finally, we will use ‘shape’, ‘colour’, … in the ggplot2 package to plot by factors. If you don’t have this package, you need to install this package or click here for download instructions. Or you can run the code below while running a program that will automatically download.

if(!require('ggplot2')) {
    install.packages('ggplot2')
    library('ggplot2')
}

And here is an example and result.

Code example:

# Import library
if(!require('ggplot2')) {
    install.packages('ggplot2')
    library('ggplot2')
}

# Create an ase
aes(mpg, wt)

# Plot
ggplot(mpg, aes(displ, model, colour=trans)) + geom_point()

Output

Another example:

# Import library
if(!require('ggplot2')) {
    install.packages('ggplot2')
    library('ggplot2')
}

# Create an ase
aes(mpg^2, wt/cyl)

# Plot
ggplot(mpg, aes(x = displ, y = hwy, shape = trans)) + geom_point()

Output

# Import library
if(!require('ggplot2')) {
  install.packages('ggplot2')
  library('ggplot2')
}

# create function using aes function
scat <- function(data, x, y) {
  ggplot(data) + geom_point(aes({{ x }}, {{ y }}))
}

cut <- function(x) cut_number(x, 3)

scat(mpg, cut(displ), drv)

Summary

So we have learned how to use and make an example of this function. If you have any questions about this function, leave a comment below, and I will answer your questions.

Good luck!

Maybe you are interested:

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *