R reverse the small lines in a ggplot with geom_rug

Viewed 100

I have a dataframe with 2 columns: date and var1. Now I want to plot these 2 variables in a ggplot and add small lines with geom_rug().

df<-tibble(date=lubridate::today() -0:14,
           var1= c(1,2.5,NA,3,NA,6.5,1,NA,3,2,NA,7,3,NA,1))

df%>%ggplot(aes(x=date,y=var1))+
  geom_point()+
  geom_rug(sides = "tr",outside = T) +
  # Need to turn clipping off if rug is outside plot area
  coord_cartesian(clip = "off")

And here is my plot:

enter image description here

But my problem is that the small lines for var1 are on the left side. I want to have them on the top.

With the argument sides= you can change the disposition of the small lines, like here:

df%>%ggplot(aes(x=date,y=var1))+
  geom_point()+
  geom_rug(sides = "t",outside = T) +
  # Need to turn clipping off if rug is outside plot area
  coord_cartesian(clip = "off")

But in this example the small lines are representing the date and not the var1. (var1 has only 10 values, but there are 15 small lines) Can someone help me, how can reverse the geom_rug-element and avoid this problem?

enter image description here

2 Answers

You do have 15 rows in df$var and in df$date. In the former, 5 are NA.

One way to approach this, is to define a limited data set with only relevant info for what is plotted (not the NAs). This should be given to geom_rug. With complete.cases we are able to omit the rows with NAs in our data set.

You could use the following code to achieve your wanted plot

library(ggplot2)
library(tibble)
library(dplyr)

df %>% ggplot(aes(x = date, y = var1)) +
  geom_point() +
  geom_rug(data = df[complete.cases(df), ] ,    ## selected date: not NA
    sides = "lt",
    outside = TRUE) +
  coord_cartesian(clip = "off")

enter image description here

please let me know whether this is what you want.

Another option if you want to drop all cases with NA values while plotting is to use the ggplot2 remove_missing() function:

df %>% ggplot(data = remove_missing(.), mapping = aes(x=date,y=var1))+
  geom_point()+
  geom_rug(sides = "t",outside = T) +
  coord_cartesian(clip = "off")
Related