Home > Blockchain >  specify drawing order with geom_line
specify drawing order with geom_line

Time:12-08

I'm trying avoid overlapping lines in a color scheme. Excuse the ugly plot, but in the following, how do I have the lines drawn in the order of y1, y2, y1Smooth, and y2Smooth?

foo <- tibble(x=1:100,y1=rnorm(100,1),y2=rnorm(100,2)) %>%
  mutate(y1Spline = smooth.spline(y1,spar=0.5)$y,
         y2Spline = smooth.spline(y2,spar=0.5)$y) %>%
  pivot_longer(cols=-x)

cols = c("darkgreen","darkblue")
ggplot(foo,aes(x=x,y=value,col=name, alpha=name))  
  geom_line()  
  scale_color_manual(values=rep(cols,each=2))  
  scale_alpha_manual(values=c(0.5,1,0.5,1))

CodePudding user response:

Practically-speaking, the order of legend items for a character variable will be equal to the order of the levels when that column is coerced into a factor. So, the default ordering is exemplified by this:

> levels(factor(foo$name))
[1] "y1"       "y1Spline" "y2"       "y2Spline"

Look familiar? The answer is to set the levels yourself before plotting:

library(ggplot2)

set.seed(8675309)
foo <- tibble(x=1:100,y1=rnorm(100,1),y2=rnorm(100,2)) %>%
  mutate(y1Spline = smooth.spline(y1,spar=0.5)$y,
         y2Spline = smooth.spline(y2,spar=0.5)$y) %>%
  pivot_longer(cols=-x)

# force factor level order
foo$name <- factor(foo$name, levels=c("y1", "y2", "y1Spline", "y2Spline"))

cols = c("darkgreen","darkblue")
ggplot(foo,aes(x=x,y=value,col=name, alpha=name))  
  geom_line()  
  scale_color_manual(values=rep(cols,each=2))  
  scale_alpha_manual(values=c(0.5,1,0.5,1))

enter image description here

A special note, the lines are drawn in that order - this means the line for "y1" will be on top of "y1Spline". If you want the lines drawn in that order, but the legend reversed, you'll need to add something like guides(color=guide_legend(reverse=TRUE)) at the end of your plot code.

  • Related