R – Line Graphs

R – Line Graphs in detail

line graph is a chart used to display information in the form of a series of data points. It utilizes points and lines to represent changes over time. Line graphs are created by plotting different points on their X and Y coordinates and joining them with a line from beginning to end. The graph represents different values that may move up and down based on the suitable variable.

Creating Line Graphs in R

The plot() function in R is used to create line graphs.

Syntax:

plot(v, type, col, xlab, ylab)

Bar Plot (Bar Chart)

bar plot in R represents values in a data vector as the height of bars. The data vector is mapped on the y-axis, and categories can be labeled on the x-axis. Bar charts can also resemble histograms when using the table() function instead of a data vector.

Syntax:

plot(v, type, col, xlab, ylab)

Parameters:

  • v: A numeric vector representing the data points.
  • type: Specifies the type of graph:
    • "p" : Draws only points.
    • "l" : Draws only lines.
    • "o" : Draws both points and lines.
  • xlab: Label for the X-axis.
  • ylab: Label for the Y-axis.
  • main: Title of the chart.
  • col: Specifies colors for the points and lines.

Example 1: Creating a Simple Line Graph

This example creates a simple line graph using the type = "o" parameter to show both points and lines.

Code:

# Create the data for the chart.
sales <- c(10, 15, 22, 18, 30)

# Plot the line graph.
plot(sales, type = "o")

Output:

Example 2: Adding Title, Color, and Labels in a Line Graph

To enhance readability, we can add a title, axis labels, and color to the graph.

Code:

# Create the data for the chart.
sales <- c(10, 15, 22, 18, 30)

# Plot the line graph with title and labels.
plot(sales, type = "o", col = "blue",
    xlab = "Month", ylab = "Sales (in units)",
    main = "Monthly Sales Chart")

Output:

To compare multiple datasets, we can plot multiple lines on the same graph using the lines() function.

Code:

# Defining a vector with counts of different fruits
counts <- c(120, 300, 150, 80, 45, 95)

# Defining labels for each segment
names(counts) <- c("Apples", "Bananas", "Oranges", "Grapes", "Mangoes", "Pineapples")

# Output to be saved as PNG file
png(file = "piechart.png")

# Creating pie chart
pie(counts, labels = names(counts), col = "lightblue",
    main = "Fruit Distribution", radius = -1,
    col.main = "black")

# Saving the file
dev.off()

Output:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *