Question

I want to create a facetted lineplot. In each subplot, one y-value (y1 or y2) is compared to the baseline. The y-value and baseline should be visualized by different colours, but this colour scheme should stay consistent within each subplot. As a legend, I only require 2 entries: "y-value" and "baseline", since the header of each subplot names the y-value to be compared.

Yet, I only got this (sample code):

library(ggplot2)
library(reshape)

df = data.frame(c(10,20,40),c(0.1,0.2,0.3),c(0.1,0.4,0.5),c(0.05,0.1,0.2))
names(df)[1]="classes"
names(df)[2]="y1"
names(df)[3]="y2"
names(df)[4]="baseline"
df$classes <- factor(df$classes,levels=c(10,20,40), labels=c("10m","20m","40m"))

dfMelted <- melt(df)
diagram <- ggplot()
diagram <- diagram + theme_bw(base_size=16)
diagram <- diagram + geom_point(data=dfMelted, size=4, aes(x=factor(classes),y=value, colour=variable, shape=variable)) 
diagram <- diagram + geom_line(data=dfMelted, aes(x=factor(classes),y=value, group=variable, colour=variable))
diagram <- diagram + facet_wrap(~ variable, ncol=1)
diagram

And this is how it looks so far: Not exactly what I want

I tried to create groups, each comprising one y-dataset and the duplicated baseline data. Then, I used facetting in terms of the group-column. Unfortunately, this results in the use of many different colours and a huge legend. Is there any better way to do this?

Was it helpful?

Solution

Is this what you had in mind?

df = data.frame(classes=c(10,20,40), y1=c(0.1,0.2,0.3), y2=c(0.1,0.4,0.5),
                baseline=c(0.05,0.1,0.2))
df$classes <- factor(df$classes, levels=c(10,20,40), 
                 labels=c("10m","20m","40m"))

# Two melts to create a grouping variable for baseline vs. new value (y1 or y2)
# and another grouping variable for faceting on y1/y2
dfm=melt(df, id.var=c(1,4))
names(dfm)[3] = "y_value"
dfm=melt(dfm, id.var=c(1,3))

ggplot(dfm, aes(x=classes, y=value, group=variable, colour=variable)) +
  geom_point() + geom_line() +
  theme_bw(base_size=16) +
  facet_grid(. ~ y_value)

enter image description here

OTHER TIPS

You are probably looking for the scale_colour_manual function:

ggplot() + 
  geom_point(data=dfMelted, size=4, aes(x=factor(classes),y=value, colour=variable, shape=variable)) + 
  geom_line(data=dfMelted, aes(x=factor(classes),y=value, group=variable, colour=variable)) + 
  scale_colour_manual(values = c("y1" = "red","baseline" = "blue","y2" = "green")) +
  theme_bw(base_size=16) + 
  facet_grid(variable ~.)

which results in: enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top