>

Danial Khosravi's Blog

Entrepreneur in the making...

Multiline Plots in R Using Ggplot2

| Comments

With the help of ggplot2, creating beautiful charts is an easy task in R. However it can get a little bit tricky when you’re trying to plot a set of data on a single chart, over a shared x axis.

A neat trick is using the library reshape2 which is a very useful data manipulation library for R. With the help of melt function of this library, we can combine our data into a single data frame in the format that ggplot2 wants from us in order to draw different lines over the same axis.

In this example, in data.csv I have function values of y=x, y=x2 and y=x3 for x values from 1 to 10 and i’m trying to draw these 3 charts on the same axis.

Note: if you haven’t installed ggplot2 and reshape2 make sure to run

1
install.packages("ggplot2")

and

1
install.packages("reshape2")
script.Rlink
1
2
3
4
5
6
7
8
9
10
11
12
library(ggplot2)
library(reshape2)

data <- read.csv('./data.csv')

chart_data <- melt(data, id='x')
names(chart_data) <- c('x', 'func', 'value')

ggplot() +
  geom_line(data = chart_data, aes(x = x, y = value, color = func), size = 1)+
  xlab("x axis") +
  ylab("y axis")

You can find the source code here on github

Comments