Basic line chart with ggplot2

ggplot2 is a package for R which easily draws plots that are easier on the eyes than R’s built-in plotting functions, though the grammar is different than what is commonly used in R. This code demonstrates how to prepare a data frame of basic math functions (logarithm, sine, etc.) and plot it with ggplot2. The code is designed to be easy to read and to adapt to real world problems.

# install ggplot2 from CRAN repository (remembered across sessions)

# load ggplot2 (required each session)

# create a data frame with basic math functions
x1to100 <- data.frame(x=1:100, val=1:100, fun='x') # linear x=x
log1to100 <- data.frame(x=1:100, val=log(1:100), fun='log') # natural log
logten1to100 <- data.frame(x=1:100, val=log10(1:100), fun='log10') # log base 10
sqrt1to100 <- data.frame(x=1:100, val=sqrt(1:100), fun='sqrt') # square root 
square1to10 <- data.frame(x=1:10, val=1:10*1:10, fun='square') # x squared, only 10 values because of scale
sin1to100 <- data.frame(x=1:100, val=sin(1:100), fun='sin') # sine
x <- rbind(log1to100,logten1to100,sqrt1to100, x1to100, square1to10 , sin1to100)

# inspect the data frame

# Prepare plot
p <- ggplot(x, aes(x=x, y=val, group=fun))

# Plot.  Add legend and color by function.  Add title.
p + geom_line(aes(color=fun)) + opts(title='Basic math functions') 

Here is the line chart (saved as a PNG using RGui’s File – Save As):


5 thoughts on “Basic line chart with ggplot2

  1. Nice post. You can accomplish the same in ggplot2 with more concise code:

    p0 = qplot(x = 1:100, geom = ‘blank’)
    funcs_to_plot = list(‘identity’, ‘sqrt’, ‘log’, ‘log10’, ‘sin’)
    p0 + llply(funcs_to_plot, function(f) {
    stat_function(fun = f, geom = ‘line’, colour = sample(600, 1))

    • Thank you. I had to look up llply: it looks like a useful function for R ninjas.

      By the way, something translated the straight quote to angle quotes, so this may work better

      p0 = qplot(x = 1:100, geom = 'blank')
      funcs_to_plot = list('identity', 'sqrt', 'log', 'log10', 'sin')
      p0 + llply(funcs_to_plot, function(f) {
      stat_function(fun = f, geom = 'line', colour = sample(600, 1))
    • You can define a custom function first, say,
      myFunc = function(x) {x^2}
      Then add ‘myFunc’ to the end of the list “funcs_to_plot”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s