1

I cannot figure out how to label each vline with year. can someone help? Below is an example of my dataset and code. I would like to label the year on the mean length vline and/or have the same colour code as the year in the figure legend.

Sector2 Family  Year    Length
BUN Acroporidae 2010    332.1300496
BUN Poritidae   2011    141.1467966
BUN Acroporidae 2012    127.479
BUN Acroporidae 2013    142.5940556
MUR Faviidae    2010    304.0405
MUR Faviidae    2011    423.152
MUR Pocilloporidae  2012    576.0295
MUR Poritidae   2013    123.8936667
NTH Faviidae    2010    60.494
NTH Faviidae    2011    27.427
NTH Pocilloporidae  2012    270.475
NTH Poritidae   2013    363.4635


require('ggplot2')
require('plyr')

ggplot(NMPSCFAM, aes(Length,  fill=Year)) + 
  geom_histogram(position="dodge", binwidth=50, colour="black") + xlim(0, 500) +
  scale_fill_grey(start = 1, end = 0)+ 

  geom_vline(data=ddply(NMPSCFAM, Year~Family~Sector2, numcolwise(mean)), 
   mapping=aes(xintercept=Length), linetype=2) + 
  xlab("Length Class") +
  ylab(expression(paste("Total Count"))) + #( ", m^2, ")", sep = 
  facet_wrap( ~ Family + Sector2, ncol=3, scales = "free")

geom_hist using ggplot and facet wrap

George
  • 1,343
  • 2
  • 12
  • 17

1 Answers1

1

To have the vlines the same colors as the bars then add argument color=Year (assuming that Year is factor in your data frame) to aes() of geom_vline() and then use scale_color_grey() with the same values as for fill.

geom_vline(data=ddply(NMPSCFAM, Year~Family~Sector2, numcolwise(mean)), 
                 mapping=aes(xintercept=Length,color=Year), linetype=2) + 
scale_color_grey(start=1,end=0)+
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • Excellent thanks so much @Didzis. Wasted an hour on this. Added the factor colours perfectly. I then removed the grid lines using theme( panel.grid.minor = element_blank(), panel.grid.major = element_blank()) – George Aug 17 '14 at 15:52