Reputation: 43
Hi I am trying to recreate the chart below in ggplot, I was wondering if someone could help me out. The highlighted red point are where it is considered a spike.
Month # of Sales Roll12 Roll26 Type 1 106 70.6 72.5 Spike 2 92 73.9 73.9 Condition 3 97 77.1 74.7 Spike 4 75 77.5 75.8 Normal 5 74 77.6 76.3 Normal 6 78 78.4 75.8 Normal 7 76 79.3 75.7 Normal 8 100 80.8 75.2 Spike 9 68 79.9 75.1 Decrease 10 73 79.3 74.9 Decrease 11 64 78.6 75.1 Decrease 12 60 77.5 74.2 Decrease
Thank you,
MS
Upvotes: 2
Views: 1201
Reputation: 3555
How about this
library("ggplot2")
library("reshape2")
df <- structure(list(Month = 1:12, Sales = c(106L, 92L, 97L,
75L, 74L, 78L, 76L, 100L, 68L, 73L, 64L, 60L), Roll12 = c(70.6,
73.9, 77.1, 77.5, 77.6, 78.4, 79.3, 80.8, 79.9, 79.3, 78.6, 77.5),
Roll26 = c(72.5, 73.9, 74.7, 75.8, 76.3, 75.8, 75.7, 75.2,
75.1, 74.9, 75.1, 74.2), Type = structure(c(4L, 1L, 4L, 3L, 3L,
3L, 3L, 4L, 2L, 2L, 2L, 2L), .Label = c("Condition", "Decrease",
"Normal", "Spike"), class = "factor")), class = "data.frame", row.names = c(NA,
-12L), .Names = c("Month", "Sales", "Roll12", "Roll26",
"Type"))
# need to convert the dataframe to long format for plotting;
# you should change the `variable.name="variable"` and `value.name="value"` args here to whatever you want to call them
df <- reshape2::melt(df, id.vars = c("Month", "Type"))
ggplot(data = df, aes(x = Month, y = value, color = variable)) +
geom_line() +
geom_point(data = df[df[["Type"]] == "Spike" & df[["variable"]] == "Sales", ], color="red")
Upvotes: 2