Need to label each geom_vline with the factors using a nested ddply function and facet wrap

浪尽此生 提交于 2019-12-08 05:06:44

问题


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")


回答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)+


来源:https://stackoverflow.com/questions/25350094/need-to-label-each-geom-vline-with-the-factors-using-a-nested-ddply-function-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!