0

I am plotting a barplot in ggplot:

ggplot(fastqc.dat,aes(y=fastqc.dat$ReadCount,x=fastqc.dat$Sample)) + geom_bar(stat="identity",position="identity",fill="darkblue") + xlab("Samples") + ylab("Read Counts") + opts(axis.text.x=theme_text(angle=-90))

My file 'fastqc.dat' looks like this:

             Sample        ReadCount
 201304950-01_ATTCAGAA_R1  27584682
 201304951-01_GAATTCGT_R1  25792086
 201304952-01_CTGAAGCT_R1  36000000
 201304953-01_GAGATTCC_R1  35634177
 201304954-01_ATTACTCG_R1  88906701

It produces the following plot: enter image description here

But I want to reorder the bars based on the read counts i.e. the Y axis. I tried a lot of things but it just won't happen. I even tried sorting fastqc.dat based on ReadCount column. Any suggestions?

Komal Rathi
  • 4,164
  • 13
  • 60
  • 98
  • I saw that question and then posted mine. The answer is not helping me. – Komal Rathi Aug 27 '13 at 20:02
  • 3
    Have a look at this recent blog post: http://trinkerrstuff.wordpress.com/2013/08/14/how-do-i-re-arrange-ordering-a-plot-revisited/ If you still can't get it post a data set we can play along and also post the code for what you've tried that hasn't worked. – Tyler Rinker Aug 27 '13 at 20:16

2 Answers2

2

... so bringing the helpful suggestions together, one solution would be:

fastqc.dat$Sample <- factor(fastqc.dat$Sample,
                            levels=fastqc.dat$Sample[order(fastqc.dat$ReadCount)])

and than use your code...

HTH

holzben
  • 1,459
  • 16
  • 24
-4

I got it to work. I had to add aes(x=fastqc.dat$Sample) to geom_bar() as below:

fastqc.dat$Sample <-factor(fastqc.dat$Sample, levels=fastqc.dat[order(fastqc.dat$ReadCount), "Sample"])

ggplot(fastqc.dat,aes(x=fastqc.dat$Sample,y=fastqc.dat$ReadCount)) + geom_bar(aes(x=fastqc.dat$Sample),stat="identity",position="identity",fill="darkblue") + xlab("Samples") + ylab("Read Counts") + opts(axis.text.x=theme_text(angle=-90))

This arranges the bars on X axis.

Komal Rathi
  • 4,164
  • 13
  • 60
  • 98
  • 3
    This is not a good solution. You should (basically) never use `$` inside of `aes()`. And the answer _is_ to reorder the levels of your factor, as in the duplicate. – joran Aug 27 '13 at 20:35