Reputation: 133
I haven't asked a question using this before so forgive me if I haven't provided what's needed/explained in sufficient detail. I'm using geom_step
in ggplot2
to try and produce step curves for data with two separate two-level factors (coded as a single four-level factor). I'd like the first factor (in the below, A vs B) to be represented by colour and the second factor (in the below, 1 vs 2) to be represented by line fill, i.e filled vs white. Here is an edited mock-up of what I'm looking for:
Is it possible to add a border to lines constructed by geom_step
in ggplot2
?
If not, could I overlay a second geom_step
line with smaller line width and different colours to "manually" add the line fill? I've tried adding another geom_step with different colours in the scale_colour_manual
term, but this simply duplicates the first geom_step
curve and returns the message "Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale."
Example code is below.
events <- rep(c(0,1,2,3,4),4)
individual <- (as.factor(rep(c("A1","A2","B1","B2"),each=5)))
step <- c(1,2,3,4,5,3,4,5,6,7,5,6,7,8,9,7,8,9,10,11)
df <- data.frame(events,individual,step)
ggplot(df, aes(x=events, group=individual, colour=individual, y=step)) +
geom_step(size=1.8) +
scale_colour_manual(values=c("green2","green2", "orange", "orange"), name="Individual")
Upvotes: 4
Views: 3995
Reputation: 1866
This isn't quite a full solution:
It's fairly easy to add a white strip by adding another geom_step command:
events<-rep(c(0,1,2,3,4),4)
individual<-(as.factor(rep(c("A1","A2","B1","B2"),each=5)))
step<-c(1,2,3,4,5,3,4,5,6,7,5,6,7,8,9,7,8,9,10,11)
filled <- rep(c(FALSE,TRUE),each=5)
data_frame<-data.frame(events,individual,step,filled)
ggplot(data_frame, aes(x=events, group=individual, colour=individual, y=step)) +
geom_step(size=1.8) +
scale_colour_manual(values=c("green2","green2", "orange", "orange"), name="Individual") +
geom_step(data=df[df$filled,], size=1.1, colour="white")
Unfortunately I'm not sure how to make the legend consistent with this.
An easier alternative would be to make some lines lighter. You can define a lighten_colour
function:
lighten_colour <- function(colour, lightness=0.5) {
# lightness should be between 0 and 1
white <- col2rgb("white") / 255
colour <- col2rgb(colour) / 255
rgb(t(white*lightness + colour*(1-lightness)))
}
... and use this for the plot colours.
ggplot(data_frame, aes(x=events, group=individual, colour=individual, y=step)) +
geom_step(size=1.8) +
scale_colour_manual(values=c(lighten_colour("green2"),
"green2",
lighten_colour("orange"),
"orange"),
name="Individual")
Upvotes: 2