3.1 C
London
Friday, December 20, 2024
HomeStatistics TutorialRHow to Plot Multiple Columns in R (With Examples)

How to Plot Multiple Columns in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Often you may want to plot multiple columns from a data frame in R. Fortunately this is easy to do using the visualization library ggplot2.

This tutorial shows how to use ggplot2 to plot multiple columns of a data frame on the same graph and on different graphs.

Example 1: Plot Multiple Columns on the Same Graph

The following code shows how to generate a data frame, then “melt” the data frame into a long format, then use ggplot2 to create a line plot for each column in the data frame:

#load necessary libraries
library(ggplot2)
library(reshape2)

#create data frame 
df #melt data frame into long format
df vars = 'index', variable.name = 'series')

#create line plot for each column in data frame
ggplot(df, aes(index, value)) +
  geom_line(aes(colour = series))

Plot multiple columns in R

Example 2: Plot Multiple Columns on Different Graphs

The following code shows how to generate a data frame, then “melt” the data frame into a long format, then use ggplot2 to create a line plot for each column in the data frame, splitting up each line into its own plot:

#load necessary libraries
library(ggplot2)
library(reshape2)

#create data frame 
df #melt data frame into long format
df vars = 'index', variable.name = 'series')

#create line plot for each column in data frame
ggplot(df, aes(index, value)) +
  geom_line() +
  facet_grid(series ~ .)

Plot multiple columns in R using ggplot2

Additional Resources

How to Create Side-by-Side Plots in ggplot2
How to Create a Grouped Boxplot in R Using ggplot2

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories