2017-10-15 3 views
0

ggplotを使ってライングラフとバープロットを結合することに問題があります。棒グラフは問題ありませんが、私が線をプロットすると、それは毎年直接に配置されます。私は代わりに各位置に最初のバープロット "C"の上にラインポイントを配置したいと思います。グラフを結合:ジオムバーと最初のバープロット上のポイントの位置を変更する方法

ありがとうございました!

tb3 <- structure(list(Year=c("2003","2005","2006","2007", 
         "2010","2012","2013", 
         "Before 2003","2003","2005", 
         "2006","2007","2010","2012", 
         "2013","Before 2003"), 
       tchtype=c("C","C","C","C","C","C", 
          "C","C","R","R","R","R", 
          "R","R","R","R"), 
       Freq=c(145,420,115,134,150,17,142, 
         33,5,3,25,23,4,134,2,237), 
       Local=c(140,393,46,29,26,2,15,2, 
         rep(NA,8))), 
      row.names=c(NA,-16L), 
      .Names=c("Year","tchtype","Freq", 
        "Local"), 
      class="data.frame") 

ggplot(data=tb3, aes(x=Year, y=Freq)) + 
    geom_bar(aes(fill=tchtype, linetype=tchtype, color=tchtype,width=.8), 
      stat="identity", position='dodge') + 
    geom_text(aes(label=Freq,group=tchtype), 
      position=position_dodge(0.8), vjust = -1, size = 3) + 
    scale_color_manual(values = c("black","black")) + 
    scale_fill_brewer(type = 'div', palette = 'Greys', direction = -1) + 
    theme_bw() + 
    geom_line(aes(x=Year, y=Local, group=tchtype)) + 
    geom_point(aes(x=Year, y=Local, group=tchtype)) + 
    ylab(label="Number of teachers") + 
    xlab("Year of appointment") + 
    theme(legend.title=element_blank(), 
     legend.position=c(.75, .75)) 

enter image description here

+0

私はあなたが取り組む最初にすべきことは、 "2003年以前" の位置にあると思います。 – neilfws

答えて

1

次のことを試してみてください。

# reorder x-axis variable 
tb3$Year <- factor(tb3$Year) 
tb3$Year <- relevel(tb3$Year, "Before 2003") 

ggplot(data = tb3, 
     aes(x = Year, y = Freq, group = tchtype, label = Freq, 
      fill = tchtype, linetype = tchtype)) + 

    # use geom_col() rather than geom_bar(stat = "identity") 
    geom_col(position=position_dodge(0.8), width = 0.8, color = "black") + 
    geom_text(position=position_dodge(0.8), vjust = -1, size = 3) + 

    # use position_dodge with the same width parameter as above 
    geom_line(aes(y = Local), position = position_dodge(0.8), show.legend = F) + 
    geom_point(aes(y = Local), position = position_dodge(0.8), show.legend = F) + 

    scale_fill_brewer(type = 'div', palette = 'Greys', direction = -1) + 

    labs(x = "Year of appointment", y = "Number of teachers") + 

    theme_bw() + 
    theme(legend.title = element_blank(), 
     legend.position = c(.75, .75)) 

plot

+0

これは本当に役に立ちます。ありがとう! – vikram

関連する問題