如何绘制线以将这些点加入ggplot?

时间:2018-12-09 20:31:06

标签: r ggplot2 data-visualization

我正在尝试使用以下代码绘制图形。

ggplot(test2, aes(x = Month, y = Spend, color = YEAR)) +
    geom_point()

输出如下所示。但是,我想加入每年的积分/抽奖线。我尝试了geom_line和geom_abline,但它们无法正常工作。我有什么办法可以做到这一点?

enter image description here

数据集:

structure(list(Month = c("01", "01", "02", "02", "03", "03", 
"04", "04", "05", "05", "06", "06", "07", "07", "08", "08", "09", 
"09", "10", "10", "11", "11", "12", "12"), YEAR = structure(c(1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("2016", "2017"), class = "factor"), 
    Spend = c(66142.27, 75735, 61247.19, 65126.4, 65947.08, 73293.63, 
    63489.61, 72500.34, 64634.54, 69689.61, 60988.69, 67231.09, 
    64966.94, 72014.3, 66683.24, 70857.17, 65637.03, 68606.12, 
    69224.13, 71083.37, 65561.6, 70094.81, 66152.87, 67784.81
    )), row.names = c(NA, -24L), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"), vars = "Month", drop = TRUE, indices = list(
    0:1, 2:3, 4:5, 6:7, 8:9, 10:11, 12:13, 14:15, 16:17, 18:19, 
    20:21, 22:23), group_sizes = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L), biggest_group_size = 2L, labels = structure(list(
    Month = c("01", "02", "03", "04", "05", "06", "07", "08", 
    "09", "10", "11", "12")), row.names = c(NA, -12L), class = "data.frame", vars = "Month", drop = TRUE))

2 个答案:

答案 0 :(得分:1)

您需要将YEAR映射到group中的geom_line美观度,因为Month是字符类型。

您必须阅读:

  

geom_path:每个组仅包含一个观察值。您需要调整小组的审美吗?

ggplot(test2, aes(x = Month, y = Spend, color = YEAR)) +
  geom_line(aes(group = YEAR)) +
  geom_point()

enter image description here

答案 1 :(得分:0)

这是解决方案:

ggplot(test2, aes(x = Month, y = Spend, color = YEAR)) +
  geom_point() + 
  geom_path(aes(group = YEAR))

geom_path是您想要的,享受