R and ggplot2

The relatively new graphing package ggplot2 looks better and is more fully-featured. Here’s some translation of typical graphs from plot to ggplot2. ggplot2 takes its direction from Leland Wilkinson’s grammar of graphics; there is data (what we want to visualize), geometry (the geometric objects used to represent data), and aesthetic attributes that are visual properties of geoms like position, color, shapes and so on.

FYI, you’ll need to install it (which you can do inside R), and then in each R session you need to load it.


Line graphs

In ggplot2

ggplot(two50, aes(x=Days, y=Likelihood)) + geom_line()

Cumulative probability distribution graph

In plot

n <- length(data$var)
plot(sort(data$var), (1:n)/n, type="s")

In ggplot2, the literatal translation would be

n <- length(data$var)
qplot(sort(data$var), (1:n)/n, stat="ecdf", geom="step")

but the idiomatic version is

ggplot(data, aes(x=var)) + stat_ecdf()

The stat_ecdf function here is from the ggplot2 package, and is the same function used in the qplot line above.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>