Data Visualization with ggplot2 (#part 1)

ggplot is based on grammer of graphics (gg), which means you can draw every graph with few basic components like:

  1. a data set
  2. a set of geom or geometry – which represents the data points
  3. a coordinate system

You can marge you data points with aes or aesthetic components to provide a beautiful graphical visualization.

For this purpose we will use the famous “iris” database.

you can simply load the iris database from R (R has inbuilt datasets to play around with the codes)

data(iris)

 

#this will load the iris data set

head(iris)

#this will let you view the headings of the data

#in ggplot, you can add arguments with ” + ” signs for every functions; for example,

Lets say we want to draw a scatter plots:

ggplot(data = iris, aes(x= Sepal.Length, y = Petal.Length)) + geom_point()


#here the ggplot is the function and iris is the data and aesthetics you can put the x-axis and y-axis data and here we are drawing scatter plot so the function we put is geom_point()

Let’s say we want to color the data points according to the species,

ggplot(data = iris, aes(x= Sepal.Length, y = Petal.Length)) + geom_point(aes(color= Species))

#For this you have to put aes in the geom point ; color = Species

Let’s say you want to change the size of points for better visualization, for that you have to add one arguments, to the geom_point; size = “which size you want”

ggplot(data = iris, aes(x= Sepal.Length, y = Petal.Length)) + geom_point(aes(color= Species, size = 2))

#Let’s say now we want to draw a density plot,

ggplot(data=iris, aes(x=Sepal.Width, fill=Species))+ geom_density(stat=”density”) +
xlab(“Sepal Width”) + ylab(“Density”) + ggtitle(“Density Plot”)

#geom_density() will allow you to plot a density plot

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s