![]() | ![]() |
Correct: Interesting lines in front of background | Wrong: Background lines obscure interesting lines |
One way to solve this is to combine the label and name columns into one column that is used to group the individual lines. In this toy example, the line belonging to group 1 should overlay the other two lines:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
df <- data.frame( n=c("a","a","b","b","c","c"), x = rep(c(1,2), 3), y = rep(c(1), 6), l = as.factor(c(1,1,0,0,0,0))) | |
# Contents of df: | |
# n x y l | |
# 1 a 1 1 1 | |
# 2 a 2 1 1 | |
# 3 b 1 1 0 | |
# 4 b 2 1 0 | |
# 5 c 1 1 0 | |
# 6 c 2 1 0 | |
# Group by n: random order of label l | |
p <- ggplot(df, aes(x,y)) + geom_line(aes(group=n, color=l)) | |
print(p) | |
# Concatenate label and name, and group by this: | |
df$o <- as.factor(apply(format(df[,c("l", "n")]), 1, paste, collapse=" ")) | |
p <- ggplot(df, aes(x,y)) + geom_line(aes(group=o, color=l)) | |
print(p) |
2 comments:
Thanks for that handy example! Another way to do that is to use the levels argument when you make l a factor:
df <- data.frame( n=c("a","a","b","b","c","c"),
x = rep(c(1,2), 3),
y = rep(c(1), 6),
l = c(1,1,0,0,0,0))
df
df$l <- factor(df$l, levels=c(1,0))
p <- ggplot(df, aes(x,y)) + geom_line(aes(group=n, color=l))
print(p)
Or you could use the relevel or reoder functions after l is created.
Cheers,
Bob Muenchen
Hi Bob, you're right, in this simple example adding making l a factor indeed helps. In my actual use case, curiously, it doesn't. But there I also specify alpha (where I have to use a continuous scale), so I'm not sure what ggplot does internally to decide the plotting order.
cheers, Michael
Post a Comment