user3437212
user3437212

Reputation: 675

How do I draw lines to join these points in ggplot?

I'm trying to plot a graph, with the following code.

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

The output looks like below. However, I want to join the points/draw line for each year. I tried geom_line and geom_abline, but they are not working. Is there any way I can acheive this?

enter image description here

Dataset:

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

Upvotes: 1

Views: 5668

Answers (2)

JayJay81
JayJay81

Reputation: 203

Here is the solution:

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

geom_path is what you were looking for, enjoy

Upvotes: 0

markus
markus

Reputation: 26373

You need to map YEAR to the group aesthetic in geom_line because Month is of type character.

You must have read:

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

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

enter image description here

Upvotes: 3

Related Questions