As we already discussed about the R graphical systems on the post The graphical Trilogy of R, this post start straight to the topic : How to plot a simple graph in R. Here I am using the basic plotting system, which is very effective and fine tuned o. The dataset used in this tutorial is “mtcars” an inbuilt example dataset in R. After this tutorial, you can able to do your plots from your own data. Let’s start the game. . .
Type mtcars on your console and check the data
You could see the datasets in console, check and have a review on how many columns, variables and void points. I hope you could remember the previous classes such as delineating desired columns and rows using various methods(check here). The simple plot here I am going to plot have two variables. Let us say ‘x’ and ‘y’.
Select one of the column in mtcars dataset as ‘x’ and other one ‘y’.
>x<- mtcars$mpg #mpg means miles/gallon(US) >y<- mtcars$hp#hp is gross horsepower
Type ?mtcars on console for more details about the data.
Now we have two variables x and y, which are shown in your global environment tab, below the values. A plot can easily generated with two sets of values by just typing :-
>plot(x,y)# you can plot any variable by delineating the column and rows >plot(mtcars$cyl,mtcars$wt)# like this
You could see a plot on the right below tab named plots.
But this is just a raw one, we need to tweak and decorate for more informative and aesthetic look.
>plot(x,y,xlab = "miles/gallons",ylab = "horsepower")# to add labels to axis >plot(x,y,xlab = "miles/gallons",ylab = "horsepower", main = "Efficiency")# to add main title
Our plot is now somewhat complete. But you can still add more tweaks and fine tune by adding a new colour or a new shape.
>plot(x,y,xlab = "miles/gallons",ylab = "horsepower", main = "Efficiency",col="red",cex=2,pch=19)
where col is obviously colour of the points,cex(character expansion) means size of the plots, pch(plotting character) defines the shape, you can check it by
Using these extra parameters you can add more information to a plot by define with datasets. For examples you could add gear types using different colours or by adding weight as the size of points.
plot(x,y,xlab = "miles/gallons",ylab = "horsepower", main = "Efficiency", col=mtcars$gear,cex=mtcars$wt,pch=19)
R is very versatile in plotting graphs, in which you could plot as you imagine. However this tutorial only help you to get started with plots in R. You could expect a great tutorial next time on multiple axis and automation.