Search code examples
rggplot2tidyversevisualizationaesthetics

Padding around geom_points in ggplot


I'm trying to replicate the plot on the left (from ggthemr package), but the closest I can get is the one on the right. Specifically, I'm trying to get one of the lines curved (like the green line in the example) while the other is straight (yellow). I'm also trying to get the padding around the geom_points so there's a bit of a gap between the points and the line.

My code for the current plot is as follows, and the data for this is down below:

    ggthemr("dust")
    
    plot <- ggplot(df, aes(x = month, y = unit, group = type)) +
        geom_line(aes(linetype = type, color = type, size = type)) +
        scale_size_manual(values=c(1.5, 1.5, 1)) +
        geom_point(aes(color = type, shape = type), size = 2) +
        scale_colour_ggthemr_d()

enter image description here

Any help would be appreciated!

Data:

df <- structure(list(type = c("Group1", "Group3", "Group2", "Group1", 
"Group3", "Group2", "Group1", "Group3", "Group2", "Group1", "Group3", 
"Group2", "Group1", "Group3", "Group2", "Group1", "Group3", "Group2", 
"Group1", "Group3", "Group2", "Group1", "Group3", "Group2", "Group1", 
"Group3", "Group2", "Group1", "Group3", "Group2", "Group1", "Group3", 
"Group2", "Group1", "Group3", "Group2"), month = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, 
6L, 7L, 7L, 7L, 8L, 8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L, 11L, 11L, 
11L, 12L, 12L, 12L), .Label = c("January", "February", "March", 
"April", "May", "June", "July", "August", "September", "October", 
"November", "December"), class = "factor"), unit = c(160.294407837043, 
256.471052539269, 405.791621951561, 93.7033481198376, 149.92535699174, 
394.453657583648, 512.563348094638, 820.101356951421, 586.017227590648, 
320.748004278314, 513.196806845303, 798.144144659107, 364.518771412572, 
583.230034260115, 561.946577331653, 338.618410043399, 541.789456069438, 
623.973070608988, 561.319198098838, 898.110716958141, 550.000251812964, 
339.53675851603, 543.258813625647, 792.931412417752, 968.459890522189, 
1549.5358248355, NA, 421.603176847263, 674.565082955621, NA, 
429.64394748425, 687.430315974801, NA, 516.598236578468, 826.557178525549, 
NA)), class = "data.frame", row.names = c(NA, -36L))

Solution

  • For the curved line, you can use the ggalt xspline function. No idea how to solve this with base ggplot btw.

    library(tidyverse)
    p <- ggplot(df, aes(x = month, y = unit, group = type)) +
           geom_line(data = . %>% filter(type != "Group1"), aes(color = type)) +
           ggalt::geom_xspline(data = . %>% filter(type == "Group1"),aes(color = type))  + 
           theme_bw()
     p
    

    enter image description here

    The padding around the geom_points can be introduced using some stroke:

    p + geom_point(aes(fill = type, ), shape = 22, color ="white", stroke=2, size=2)
    

    enter image description here