Line Plots In R And ggplot2

Hi. Here is some work that I have done with line plots in R and ggplot2.


Table Of Contents

Belgian Phone Calls Data

A Simple Line Plot

Some Variations Of The Line Plot

References


Belgian Phone Calls Data

The dataset that I have chosen for this is on Belgian phone calls data from 1950 to 1973. The R documentation has this information about this dataset.

 

To start, load the libraries MASS and ggplot2.

From the MASS dataset library, there is a dataset called phones. This phones data is saved into a variable called belgium_phonecalls.

The head() and tail() functions are used to look at a small sample of the data.

I do not like the year values with the last digits only. Adding 1900 to the first column would be ideal here. Also, I rename the column names using colnames().

 


A Simple Line Plot

Using the ggplot2 package in R, a simple line plot can be created from our data table.

One can easily see that the number of phone calls (in millions) has increased dramatically starting at around 1963 to about 1968. Someone with domain knowledge of Belgium and the phone industry would likely know what contributed to the increase and decrease number of phone calls from around 1963 to 1970.


Some Variations Of The Line Plot

The neat thing about ggplot2 in R is that it provides more variety and more choice for the R user/programmer. Here are some variations of the line plot.

If I want to add data points with the line, I simply add geom_point with geom_line() on top of the ggplot() function saved in plot.

The points above are somewhat small and the colour could be changed. Here is a different version of the above.

The line colour has been changed to dark green and the points have a different size, shape and are now blue.

To make the plot more complete, labels and other features need to be added. Here is the code and output.


References

R Graphics Cookbook by Winston Chang (2012)

R Documentation in the faraway package.

Leave a Reply