Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ggplot2 plots prettier?

Tags:

plot

r

ggplot2

I have generated the following plot using the R code that follows it: alt text

ggplot(lengths, aes(length, fill = library)) + geom_density(alpha = 0.2) + coord_cartesian(xlim = c(0, 60000)) 

Now I would like to make the plot a bit prettier:

  1. Make the x-axis show length every 5000 units (instead of every 20000)
  2. Add x-values on top of the three peaks (approx 3000,5000 and 35000).

How can I do that?

update in response to James: alt text

like image 362
David B Avatar asked Aug 31 '10 07:08

David B


People also ask

Is ggplot2 better than Matplotlib?

Both packages achieved very similar results. But the contour lines, labels, and legend in matplotlib are superior to ggplot2.

What is the difference between Ggplot and ggplot2?

You may notice that we sometimes reference 'ggplot2' and sometimes 'ggplot'. To clarify, 'ggplot2' is the name of the most recent version of the package. However, any time we call the function itself, it's just called 'ggplot'.


1 Answers

How about:

(first create a reproducible example)

set.seed(1001)
lengths <- data.frame(length=c(rgamma(1000,shape=10,scale=500),
                    10000+rgamma(1000,shape=5,scale=700),
                    rnorm(500,mean=30000,sd=2000)),
                  library=factor(rep(2:1,c(2000,500))))

(cute stuff to find peak locations and heights)

peakfun <- function(x) {
  d <- density(x$length)
  peaks <- which(diff(sign(diff(d$y)))==-2)
  data.frame(x=d$x[peaks],y=d$y[peaks])
}

peakdat <- ddply(lengths,.(library),peakfun)
peakdat <- peakdat[-1,] ## drop spurious peak

(draw the plot)

library(ggplot2)
ggplot(lengths, aes(length, fill = library)) +
  geom_density(alpha = 0.2) +
  scale_x_continuous(limits = c(0,60000),
                     breaks = seq(0,60000,by=5000))+
  geom_text(data=peakdat,aes(x=x,y=y,label=round(x)),vjust=1)

you probably want to tweak the vertical height of the labels a little

like image 57
Ben Bolker Avatar answered Sep 23 '22 17:09

Ben Bolker