Line chart with smoothed conditional mean

By Data Tricks, 6 August 2018

Last modified 6 September 2019

Create data and set-up theme

data <- data.frame(Month = rep(1:100, each=1, times=3))
data$Add <- sample(-10:15, 300, replace=TRUE)
data$Category <- rep(1:3, each=100, time=1)
data <- data %>%
group_by(Category) %>%
theme <- theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line.x = element_line(color="#919191", size = 0.1),
axis.line.y = element_line(color="#919191", size = 0.1))

Line chart with smoothed conditional mean

#Multiple line chart with smoothed conditional mean
data$Category <- as.character(data$Category) # convert the Category to a character
gg <- ggplot(data, aes(x=Month, y=Value, colour=Category))
gg <- gg + geom_point()
gg <- gg + geom_smooth(alpha=0.3, method="loess", span=0.2)
gg <- gg + theme

The span attribute controls the amount of smoothing for the default loess smoother. Smaller numbers produce wigglier lines, larger numbers produce smoother lines. Changing span to 5 in the above example produces the following chart.

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that your first comment on this site will be moderated, after which you will be able to comment freely.