[This article was first published on The Jumping Rivers Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)


Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This is part 2 of an ongoing series on why you should use R. Futureblogs will be linked here as they are released.

  • Part 1: Why should I use R: The Excel R Data Wrangling comparison:Part1

Why create plots in R and not Excel? To a programmer this may seem likea very obvious question, but it is still a common question asked byExcel users — If you have a data set, could you select it, hit a coupleof buttons and generate plots? This is one of the trickiest questions toanswer, especially if you have limited Excel experience as many new agedata scientists do. Hopefully, some of the reasons below will encourageyou to make the switch from Excel to R.

ReproducibilityHow do you view the code used to generate the Excel graph? Are you ableto tell exactly whats going on? Are you able to control and modify allof the aesthetics of the plot, such as changing the length of the axisticks, or changing the font? If yes, are you able to share your workwith a colleague and have them easily replicate your plot without youtelling them where to click and which modification should be applied?

With R all of these things are possible. You automatically have all thecode visible in the form of scripts. Reading and understanding the codeis possible because of its easy to read syntax, which allows you totrack what the code is doing without having to be concerned about anyhidden functions or modifications happening in the background.


Do you require help building a Shiny app? Would you like someone to take over the maintenance burden?If so, check outour Shiny and Dash services.


Understanding changesIn Excel it is challenging to eye-ball which changes have been made to agraph, especially if these were minor changes. With R (and some easy touse version control systems), you can see exactly which files werechanged. Also, in Excel, a user would usually draw a graph on a singleExcel document, and if the same graph is required on a different dataset, it is common to copy-and-paste a bunch of manipulations andconfigurations to another document. Such repeated human interaction isprone to introducing errors, as well as consuming a large amount oftime. With R we can avoid this by creating functions, which can be usedto run the same code on different data sets simply by changing theinput, thereby producing reliable outputs and saving us a lot of time.

ExtensibilityYes, Excel has a wide range of basic graphics available, but R has a lotmore. Excel has been around for a while, so it has some decent toolsthat have been developed over the years. R, however, is open source, andtherefore extensions are widely available – it’s even fairly easy tomake your own. R also has thousands of libraries that can be used toeasily produce graphics without all the pre-graph work to create somereally crafty stuff. With that being said, Excel is perfectly sufficientwhen creating basic, simple, straight forward plots. But what if we’renot looking to be basic?

The simplicity of RThe package {ggplot2} is a plottingpackage in R that provides us with commands to create complex plots. R’scommand line interface let’s you quickly select x- and y-axis labels,colour by variables, modify grid lines and much more. Each item is addedin a new layer, which allows us to add in and remove graph elementswithout affecting the rest of the plot. Interested in changing thecolour gradient/scale of your plot? No problem, just use a packagecalled{RcolourBrewer},which helps you select sensible colour schemes for your plots.Interested in changing the title of your plot? Simply add a layer calledggtitle – and so much more.

The comparisonLet’s create some simple plots in Excel and then create a similar plotin R using the {ggplot2} functions. Hopefully, by the end of this post,we’ll have motivated you to switch to R. Now, let’s get started byloading the data and packages. The data set that we’ve used below isdata from a selection of movies, and is comprised of five columns:country, year, highest profit gained per movie, number of moviesproduced and number of employees on set during production.

library("ggplot2") # For plottinglibrary("viridis") # Provides a range of colour paletteslibrary("readr") # For loading data library("tidyverse") # For data wranglingmovies\_data <- read\_csv("blog\_data.csv") Let’s start by creating a scatter plot, in which we compare the numberof employees present in the different countries within each year.

Scatter PlotExcelThe scatter plot generated in Excel was simple to create, but everythinghad to be done manually: selecting the data and the variables for the x-and y-axis and then selecting the type of plot. I was also required tomanually change the axes titles. If we were interested in changing thegrid lines, this would have to be done manually too. Looking at thisplot, is this something that you are able to easily recreate? Would youknow where to point and click to generate this visualisation?

RHere we created a similar plot in R using the {ggplot2} functions.Because the code is visible we can easily recreate the plot above, butalso, we are able to conveniently see which functions and aestheticswere applied to our plot.

ggplot(data = movies\_data, aes(x = Year, y = no\_employees)) + geom\_point(aes(colour = Country)) + labs(x = "Years", y = "Number of employees", colour = "Country") + theme\_bw() Theming system in {ggplot2}Theme arguments specify the non-data features that you can control. Forexample, the axis.text argument controls the appearance of the axistext such as the font size, colour and face of text. The axis.ticks.xcontrols the ticks on the x-axis and so on. The theme() functionallows you to override the default theme elements, liketheme(plot.title = element_text(colour = "red")). Completethemes, liketheme_bw(), set all of the theme elements to values designed to worktogether.

We can take this plot even further. Let’s say we were interested increating the same plot as above, but with each country having its ownplotting panel within the same visualisation. We can use the facetfunction from the {ggplot2} package:

ggplot(data = movies\_data, aes(x = Year, y = no\_employees)) + geom\_point() + facet\_wrap(~Country, ncol = 4) + labs(x = "Years", y = "Number of employees") + theme\_bw() + theme(axis.text.x = element\_text(angle = 45, vjust = 1, hjust = 1)) We have also utilised the axis.text.x element to adjust the angle andposition of the x-axis labels to ensure that they are legible. Are youable to create this in Excel without copying and pasting the graphs? Ifso please do show us how you were able to do this.

Now, let’s proceed to create a histogram using Excel and R. Looking atthe theme() function alone, we can see that R has a lot more featuresavailable that we are able to modify, such as axes text, fonts, legendsize and grid lines. As a data enthusiast, which graph looks moreaesthetically pleasing to you?

Histogram PlotExcelThe histogram generated below was a bit more time consuming. Firstly, wehad to change the size of the bars in a normal bar graph in order togenerate a histogram. The colours of each column had to manually beselected and applied. Adding a legend to this plot was also a manualprocess. Looking at this plot, is this something that you are able toeasily recreate?

Now, let’s generate a histogram using R and its {ggplot2} functions.

ROnce again, it is evident that we can easily control all of thevariables and aesthetics of the histogram plot generated using ggplot.Here we used a new function called thescale_fill_viridis()which is a function for {ggplot2} which allowed us to modify the coloursvisible on the histogram bars. We also used the theme_classic()function in R to create a classic looking plot with x- and y-axis linesand no gridlines. We also edited the size, colour and font of the texton the axes (axis.text).

ggplot(data = movies\_data, aes(x = Highest\_profit)) + geom\_histogram(aes(fill = Country)) + labs(x = "Yearly profit (in million dollars)", y = "Count") + scale\_fill\_viridis(discrete = T) + theme\_classic()+ labs(colour = "Country") + theme( axis.text = element\_text(size = 10, colour = "black", family = "serif") ) Now, let’s move on and generate our last plot.

Line PlotExcelThe line plot was the most complex plot to create. Firstly, whengenerating the line graph, it was evident that the data within the yearcolumn had to be rearranged in ascending order or it will put theearlier years after the later years. The line graph was also not able toplot more than one graph representing each country as a different lineas some countries did not have data for all the years. After a lot offrustration with Excel we attempted to create a very basic line plot inR.

RWith only three lines of code and very little frustration, we wereeasily able to recreate the line graph above in R.

ggplot(data = movies\_data, aes(x = Year, y = Number\_movies)) + geom\_line(aes(colour = Country)) + labs(x = "Years", y = "Number of movies produced") Now, let’s add some more aesthetics to our plot as we did for theprevious ones by changing the font size (axis.title and axis.text),changing the panel border (panel.border), as well as editing thelegend size (legend.key.size). Here we decided to use thetheme_dark() function in R to create a dark background, which iscommonly used to make thin coloured lines pop out.

ggplot(data = movies\_data, aes(x = Year, y = Number\_movies)) + geom\_line(aes(colour = Country)) + labs(x = "Years", y = "Number of movies produced") + labs(colour = "Country") + theme\_dark() + theme( panel.border = element\_rect(colour = "black", fill = NA, size = 2), axis.title = element\_text(size = 12, face = "bold", family = "Arial"), axis.text = element\_text(size = 10, colour = "black", family = "Arial"), legend.key.size = unit(0.50, "cm") ) When comparing R and Excel, it’s important to define the level ofinformation you are looking for. If you want to run basic statisticsquickly, Excel might be the better choice. If you are interested increating a very basic graph, Excel may be the better choice, due to itseasy point-and-click system. Before plotting a graph ask yourself; “Howdetailed does my visualisation need to be? Am I creating a plot for apublication or not? In Excel it is evident that we can easily select achunk of data and make a simple chart, however, when making morecomprehensive plots, using Excel can be extremely frustrating and timeconsuming. It all comes down to what you need your graphics to do. Forthose planning to publish large amounts of complicated data, spendingthe time in R to create impressive visual representations will certainlybe worth your time. It is also clear that R is not difficult, and givesyou the option to customise more than Excel.

R and Excel are beneficial in different ways. Excel starts off easier tolearn and is the go-to program when we are exposed to computers and someof us end up being stuck there. However, R is designed to bereproducible which is clearly of high importance. It’s not a question ofchoosing between R and Excel, but deciding which program to use fordifferent needs.

If you’re interested in learning how to create graphs using R, thenattend our Data visualisation withggplot2course.

For updates and revisions to this article, see the original post

To leave a comment for the author, please follow the link and comment on their blog: The Jumping Rivers Blog.


R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.


Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.Continue reading: Why should I use R: The Excel R plotting comparison: Part 2