How to Create a Line Graph in RStudio

A line graph is a type of graph that displays information as a series of data points connected by straight lines. It’s particularly useful for analyzing changes over time, especially when comparing values across months, quarters, or years. In this tutorial, you’ll learn how to create a line graph in R Studio using three commonly used tools: base R, ggplot2, and plotly. As an example, we’ll use a simple dataset that shows toy sales over time:

year <- 2015:2024
sales <- c(120, 150, 170, 160, 180, 210, 250, 270, 300, 330)
my_data <- data.frame(year, sales)

Method 1: Create a Line Graph with Base R

To create a line graph using base R, we use the plotfunction:

plot(x=my_data$year, y=my_data$sales, 
     type = "o", col = "darkblue", lwd = 3,
     pch = 18, cex = 1.5, xlab = "Year", 
     ylab = "Sales", main = "Annual Sales Trend", 
     cex.axis = 0.65, font.lab = 2)    
grid()
Line Graph in R Studio using Base R

Here’s a breakdown of what each part of the code does:

  • x = my_data$year specifies years as the x-axis variable
  • y = my_data$sales specifies sales as the y-axis variable.
  • type = "o" tells R to plot both lines and points. The line connects the data, and the points show each data value.
  • col = "darkblue" sets the color of both the points and the line to dark blue.
  • lwd = 3 increases the thickness of the line to make it more prominent.
  • pch = 18 chooses a diamond shape for the plot points.
  • cex = 1.5 enlarges the points to 1.5 times their default size.
  • xlab = "Year" sets the label for the x-axis to “Year”.
  • ylab = "Sales" sets the label for the y-axis to “Sales”.
  • main = "Annual Sales Trend" adds a title to the plot.
  • cex.axis = 0.65 reduces the size of the axis tick labels for better spacing.
  • grid() adds grid lines to the plot to improve readability and alignment.

Method 2: Create a Line Graph with Ggplot2 Package

While base R is great for quick visualizations, the ggplot2 package is the industry standard for creating polished, professional-grade graphics. Here’s how to create a ggplot2 version of this line graph:

# Installing the ggplot2 package:
install.packages("ggplot2")
# Loading the ggplot2 library:
library(ggplot2)
# Creating the line graph:
ggplot(my_data, aes(x = year, y = sales)) +
  geom_line(color = "darkblue") +
  geom_point(color = "darkblue") +
  scale_x_continuous(breaks = seq(2015, 2024, by = 2)) +  
  ggtitle("Sales Over Time") +
  xlab("Year") + 
  ylab("Sales")+
  theme(
    plot.title = element_text(face = "bold"),
    axis.title.x = element_text(face = "bold"),
    axis.title.y = element_text(face = "bold")
  )
Line Graph in R Studio using Ggplot Package

Let’s take a closer look at each code component:

  • install.packages("ggplot2") installs the ggplot2 package, library(ggplot2) loads the ggplot2 package so you can use the functions.
  • ggplot(my_data, aes(x = year, y = sales)) initializes the plot with the my_data dataframe and maps year to the x-axis and sales to the y-axis.
  • geom_line(color = "darkblue") adds a line connecting the data points, with the line color set to dark blue.
  • geom_point(color = "darkblue") adds individual points at each data location, also in dark blue.
  • scale_x_continuous(breaks = seq(2015, 2024, by = 2)) sets the x-axis to display ticks at 2-year intervals from 2015 to 2024.
  • ggtitle("Sales Over Time") adds the plot title “Sales Over Time”.
  • xlab("Year") adds a label “Year” to the x-axis.
  • ylab("Sales") adds a label “Sales” to the y-axis.

Method 3: Create a Line Graph with Plotly Package

If you want to take your data visualization to the next level, the Plotly package is an excellent choice. It creates interactive web-based charts that allow your audience to explore the data directly. Use the following code to build an interactive line graph:

# Installing the plotly package:
install.packages("plotly")
# Loading the plotly library:
library(plotly)
# Creating the line plot:
fig <- plot_ly(
  data = my_data,
  x = ~year,
  y = ~sales,
  type = 'scatter', 
  mode = 'lines+markers',
  line = list(color = 'darkblue', width = 2),
  marker = list(size = 6.5, color = 'darkblue')
) %>%
  layout(
    title = list(
      text = "Sales Over Time",
      font = list(size = 16)
    ),
    xaxis = list(
      title = "Year",
      tickvals = seq(2015, 2024, by = 2),
      titlefont = list(size = 14),
      tickfont = list(size = 12)
    ),
    yaxis = list(
      title = "Sales",
      titlefont = list(size = 14),
      tickfont = list(size = 12)
    )
  )
fig
Line Graph in R Studio using Plotly Package

To understand how this interactive plot is built, here is a breakdown of the code:

  • install.packages("plotly") installs the plotly package, library(plotly) loads the plotly package so you can use its functions
  • plot_ly(...) generates a line plot with markers using the Plotly package. Although the plot type is set to scatter, the mode = 'lines+markers' option tells Plotly to connect the data points with lines and also display individual points as markers. The argument data = my_data tells Plotly to use the my_data dataset as the source for the plot, the argument x = ~year maps year to the x-axis, the argument y = ~sales maps sales to the y-axis, the arguments color = 'darkblue', width = 2 set the line color to dark blue and the width to 2, while the arguments size = 6.5, color = 'darkblue' adjust the marker size to 6.5 and also sets the color to dark blue.
  • layout(...) customizes the appearance of the plot’s title and axes. The argument title = list(...) sets the main title of the plot to “Sales Over Time” with a font size of 16. The xaxis = list(...) section defines the properties of the x-axis: title = "Year" labels the axis as “Year,” tickvals = seq(2015, 2024, by = 2) specifies the tick positions at every 2-year interval from 2015 to 2024, titlefont = list(size = 14) sets the axis title font size to 14, and tickfont = list(size = 12) sets the size of the tick labels to 12. Similarly, the yaxis = list(...) section defines the y-axis with title = "Sales" as its label, and sets both the axis title and tick label font sizes to 14 and 12, respectively.

Need Help from an R Tutor?

If you’re finding it challenging to create or customize line graphs in RStudio, working with an experienced tutor can save you time and make learning R a more enjoyable, less stressful experience. Visit our R Tutor page to learn more about our one-on-one tutoring services and assignment assistance.