Search code examples
rggplot2flags

ggplot with multiple flags


I have a basic data set that includes several flags:

library(ggplot2)
X<-c(seq(1:10))
Y<-c(2,4,6,3,5,8,6,5,4,3)
Flag1<-c(0,0,0,0,1,0,0,1,0,0)
Flag2<-c(0,0,0,0,60,0,0,0,0,60)
Flag3<-c(12,0,12,12,12,12,12,0,0,12)
Flag4<-c(0,0,0,0,40,0,0,40,0,0)

DF<-data.frame(X,Y,Flag1,Flag2,Flag3,Flag4)

Each Flag Type (1-4) contains either a "0", or a number specific to that flag type. My goal is to plot the above x/y data as a basic line plot

p<-ggplot(DF, aes(x=X, y=Y)) +geom_line() +geom_point(col='black', size=1)

But than overlay points on the plot to mark where I have flags. Ideally the flag points would be slightly larger, and each Flag type would be a different color.

Some of my flag points will overlap, so I'm not sure what is the most aesthetically pleasing way to deal with that (maybe an offset to keep the points from overlapping?)


Solution

  • You can try reshaping the data from wide to long, i.e. create columns for flag type and flag value. Then you can colour by flag type and use size for flag value. One way to avoid overlap is geom_jitter.

    library(tidyr)
    library(ggplot2)
    DF %>% 
    gather(flag, value, -X, -Y) %>% 
      ggplot(aes(X, Y)) + geom_line() + geom_jitter(aes(color = flag, size = value))
    

    Result: enter image description here

    Another alternative is to use facet_grid for separate plots by flag type.