geom_line不会在barplot中绘制

时间:2014-01-15 12:22:14

标签: r ggplot2

我想制作一个包含两行grpah的条形图。我的数据输入:

structure(list(month = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), .Label = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), class = "factor"), aantal = c(84, 85, 83, 97, 104, 97, 65, 69, 63, 55, 65, 77, 84, 85, 83, 97, 104, 97, 65, 69, 63, 55, 65, 77, 84, 85, 83, 97, 104, 97, 65, 69, 63, 55, 65, 77, 84, 85, 83, 97, 104, 97, 65, 69, 63, 55, 65, 77), gem.mag = c(1.36, 1.44, 1.21, 1.13, 1.25, 1.29, 1.34, 1.38, 1.33, 1.37, 1.31, 1.25, 1.36, 1.44, 1.21, 1.13, 1.25, 1.29, 1.34, 1.38, 1.33, 1.37, 1.31, 1.25, 1.36, 1.44, 1.21, 1.13, 1.25, 1.29, 1.34, 1.38, 1.33, 1.37, 1.31, 1.25, 1.36, 1.44, 1.21, 1.13, 1.25, 1.29, 1.34, 1.38, 1.33, 1.37, 1.31, 1.25), temp = c(3.1, 3.3, 6.2, 9.2, 13.1, 15.6, 17.9, 17.5, 14.5, 10.7, 6.7, 3.7, 3.1, 3.3, 6.2, 9.2, 13.1, 15.6, 17.9, 17.5, 14.5, 10.7, 6.7, 3.7, 3.1, 3.3, 6.2, 9.2, 13.1, 15.6, 17.9, 17.5, 14.5, 10.7, 6.7, 3.7, 3.1, 3.3, 6.2, 9.2, 13.1, 15.6, 17.9, 17.5, 14.5, 10.7, 6.7, 3.7), difftemp = c(14.9, 14.7, 11.8, 8.8, 4.9, 2.4, 0.1, 0.5, 3.5, 7.3, 11.3, 14.3, 14.9, 14.7, 11.8, 8.8, 4.9, 2.4, 0.1, 0.5, 3.5, 7.3, 11.3, 14.3, 14.9, 14.7, 11.8, 8.8, 4.9, 2.4, 0.1, 0.5, 3.5, 7.3, 11.3, 14.3, 14.9, 14.7, 11.8, 8.8, 4.9, 2.4, 0.1, 0.5, 3.5, 7.3, 11.3, 14.3), mag.cat = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4), value = c(19, 27, 32, 46, 40, 36, 23, 27, 22, 18, 19, 25, 58, 46, 45, 46, 58, 52, 35, 28, 34, 32, 39, 44, 7, 10, 6, 5, 6, 8, 6, 12, 7, 3, 7, 8, 0, 2, 0, 0, 0, 1, 1, 2, 0, 2, 0, 0)), .Names = c("month", "aantal", "gem.mag", "temp", "difftemp", "mag.cat", "value"), row.names = c(NA, 48L), class = "data.frame")

我尝试使用以下代码绘制条形图中的两条线:

ggplot(maand.long) + 
  geom_bar(aes(x = month, y = value, fill = as.factor(mag.cat)), 
           stat = "identity", width = 0.7) +
  geom_hline(yintercept = mean(maand.long$aantal), size = 1, color = "red") +
  geom_line(aes(x = month, y = difftemp))

绘制了hline,但法线不是。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

ggplot尝试为month的每个级别绘制一条线,因为此变量是一个因素。有两种方法可以解决这个问题:

  1. 使用as.numeric

    geom_line(aes(x = as.numeric(month), y = difftemp))
    
  2. 使用group = 1

    geom_line(aes(x = month, y = difftemp, group = 1))
    
  3. 完整的代码:

    ggplot(maand.long) + 
      geom_bar(aes(x = month, y = value, fill = as.factor(mag.cat)), 
               stat = "identity", width = 0.7) +
      geom_hline(yintercept = mean(maand.long$aantal), size = 1, color = "red") +
      geom_line(aes(x = month, y = difftemp, group = 1))
    

    enter image description here