Introduction
Line and area charts are two popular visualizations used to represent data over time. Line charts display data points connected by straight lines, showing trends over time. While area charts are similar to line charts but fill the area beneath the lines with color or shading - emphasizing the volume of data over time.
In this short article, I will be demonstrating how to create line and area charts using the ggplot2 package - a powerful and flexible data visualization package that allows users to build plots layer by layer using the Grammar of Graphics.
Creating line chart
To create a line chart in ggplot2, first you need to load the necessary packages in your R session.
Next, set the working directory and load the dataset. In this case, I will be using the Sample – Superstore dataset.
With data loaded, using mutate() function I am going to compute Month Year (my) values using the code below.
Note: Month Year (my) values will be essential when plotting Sales generated by month of the year.
Note, the above code adds a new column “my” in the data as shown below.
To plot the Sales by month of the year, you can use the following simple code.
Note: In the above code, I have summarized the Sales values using SUM, meaning that I am adding all the Sales values per Month Year (my).
Executing the above code results in.
Let’s customize the view by making the line thicker, changing the color of the line from default to “brown”, and use the classic theme to declutter the view.
Executing these results in.
Note: You can plot multiple line charts by making a few adjustments into the code. For example, in this case, I can plot the trend of Sales by Month Year by Region -by simply specifying color as region in the aesthetic section as shown below.
Executing the above code results in.
Creating area chart
Using the same data, you can visualize Monthly Sales as an area chart by making a simple change such as replacing geom_line() with geom_area() function in the code as shown below.
Executing the above code results in.
Let’s customize the view by coloring the line “brown” and shade the area below the line in “gray” and apply the classic theme to declutter the view using the code below.
Executing the above code results in.
Conclusion
Choosing between a line chart and an area chart depends on the specific needs of your data visualization. If your goal is to track precise trends and compare multiple datasets, a line chart is ideal. Conversely, if you want to emphasize the volume of data over time or show how parts contribute to a whole, an area chart may be more appropriate. Each chart type has its strengths and weaknesses, making them complementary tools in data visualization.
If you like the work we do and would like to work with us, drop us an email on our contacts page and we’ll reach out!
Thank you for reading!