组合图:geom bar和指向如何在第一个条形图上更改点的位置

时间:2017-10-15 21:37:51

标签: r ggplot2 bar-chart

我正面临使用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

1 个答案:

答案 0 :(得分: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