Ggplot2: Bring one line forward, but keep colors

Consider the following code:

library(ggplot2) foo <- data.frame(x=1:10,A=1:10,B=10:1) ggplot(melt(foo,id.vars="x"),aes(x,value,color=variable))+geom_line(size=5) 

enter image description here

I want the red line (A) to be in front, above B (see the cross point), and the colors and order that they display in the legend do not change. Is there any way?

+6
source share
4 answers

Try it,

 last_plot() + aes(group=rev(variable)) 
+10
source

Replacing the red line using a subset of the data does the trick.

 library(ggplot2) foo <- data.frame(x=1:10,A=1:10,B=10:1) require(reshape2) fooM <- melt(foo,id.vars="x") p<-ggplot() p<-p+geom_line(data=fooM[fooM$variable!="A",],aes(x,value,color=variable),size=5) p<-p+geom_line(data=fooM[fooM$variable=="A",],aes(x,value,color=variable),size=5) p 

EDIT: Note that ggplot sequentially applies layers to each other - this is best used when plotting lines by lines.

EDIT2: @tonytonov is right that you can avoid duplicate repeating the same thing. Modified my answer to draw everything except A for the first time, then only A. The result remains the same, and now it is also compatible with transparency or big data;)

+3
source

A relay solution is great if you have no reason to avoid it. I can imagine at least two: the use of alpha (transparency) or performance problems (you need to do this in one pass, big data).

Here is what I suggest:

 require(scales) # give the desired order here, I just use reverse # separate function since we apply it over both levels & colors shuffle <- function(x) rev(x) foo <- data.frame(x=1:10, A=1:10, B=10:1, C=2.5, D=7.5) melt_foo <- melt(foo, id.vars="x") # original plot ggplot(melt_foo, aes(x, value, color=variable)) + geom_line(size=5) 

enter image description here

 orig_order <- levels(melt_foo$variable) new_order <- shuffle(orig_order) # grabbing default colours orig_colors <- hue_pal()(length(new_order)) new_colors <- shuffle(orig_colors) melt_foo$variable <- factor(melt_foo$variable, levels=new_order) # levels _and_ colours reversed, legend appearance stays the same ggplot(melt_foo, aes(x, value, color=variable)) + geom_line(size=5) + scale_colour_manual(values=new_colors, labels=orig_order, breaks=orig_order) 

enter image description here

+2
source

The order of your A,B inside the data.frame(x=1:10,A=1:10,B=10:1) causes this layering problem because it draws A first (1:10).

If you use data.frame(x=1:10,A=10:1,B=1:10) , an ascending line from above will be inserted (since B is drawn last).

0
source

All Articles