How to make ggplot2 plots prettier?

前端 未结 2 1074
有刺的猬
有刺的猬 2021-02-09 04:08

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

ggplot(lengths, aes(leng         


        
相关标签:
2条回答
  • 2021-02-09 04:50

    1: + scale_x_continuous(breaks=rep(5000,12)).

    You could also put the xlim declaration in here, using limits, eg,

    + scale_x_continuous(breaks=rep(5000,12),limits=c(0,60000))
    

    2: For the labels you could use annotate() or geom_text(). See this post for examples. You would have to calculate the values yourself for this though.

    0 讨论(0)
  • 2021-02-09 05:09

    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

    0 讨论(0)
提交回复
热议问题