How to Create a Line Chart in R

Here are 2 ways to create a line chart in R:

(1) Using the base R plotting functions:

# Sample data
x <- c(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
y <- c(2, 4, 6, 9, 12, 15, 16, 13, 7, 5)

# Build the line chart
plot(x, y, type = "l", col = "blue", lwd = 2, xlab = "X-axis label", ylab = "Y-axis label", main = "My Line Chart")

Where:

  • x represents the x-axis values
  • y represents the corresponding y-axis values
  • type = “l” represents a line chart
  • col = “blue” represents the line color
  • lwd = 2 represents the line width

(2) Using the ggplot2 package:

First install the ggplot2 package:

install.packages("ggplot2")

Then apply the following script:

library(ggplot2)

# Sample data
data <- data.frame(
  x = c(1, 3, 5, 7, 9, 11, 13, 15, 17, 19),
  y = c(2, 4, 6, 9, 12, 15, 16, 13, 7, 5)
)

# Build the line chart
ggplot(data, aes(x = x, y = y)) +
  geom_line(color = "blue", size = 1) +
  labs(x = "X-axis label", y = "Y-axis label", title = "My Line Chart")

Additional customization:

library(ggplot2)

# Sample data
data <- data.frame(
  x = c(1, 3, 5, 7, 9, 11, 13, 15, 17, 19),
  y = c(2, 4, 6, 9, 12, 15, 16, 13, 7, 5)
)

# Build the line chart
ggplot(data, aes(x = x, y = y)) +
  geom_line(color = "blue", size = 1) +
  labs(x = "X-axis label", y = "Y-axis label", title = "My Line Chart") +
  theme_minimal() +
  theme(
    plot.title = element_text(size = 20, face = "bold", color = "darkblue", hjust = 0.5), 
    axis.text = element_text(size = 14, color = "black"),
    axis.title = element_text(size = 14, color = "black"),
    panel.background = element_rect(fill = "lightgray"),
    panel.grid.major = element_line(color = "white"),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  )