Reputation: 9018
I have a graph that look like this:
x = c( rep(c(1,2,3,4,5),4) )
group = c( rep(c(10,10,10,10,10),2),rep(c(20,20,20,20,20),2) )
value = rnorm(20)
dat = data.frame( x= x , group = group, value = value)
dat = dat %>% # create the mu, sd, q1 and q3 aggregates
group_by(group,x) %>%
summarise(mu = round(mean(value),2),
sd= sqrt(round(sd(value),2)),
Q1 = quantile(value)[2],
Q3 = quantile(value)[4],
count = n())
dat
dat2 = dat %>% gather (key = Metric, value= Value,c(mu, sd, Q1, Q3)) #melt the data
as.data.frame(dat2)
ggplot(data=dat2 , aes(x=x, y=Value, group = Metric,colour = Metric)) +
geom_line() + geom_point() + ylab("value") +
xlab("v") +
scale_x_discrete(breaks = c( seq(1,5,1) ) ) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_y_continuous(breaks = c( seq(-3,3,.25) ) ) +
scale_colour_manual(values=c("blue", "blue", "red","red")) +
facet_wrap(~ group, ncol=3)
For each group the lines are the sd, mean, 1st and 3rd quartiles. I would like the mean and sd to be BLUE and the 1st and 3rd quartiles to be RED. You can see that the colors are not correct.
(1) How can I control the colors of the lines so that sd and mean are blue and quartiles are red?
(2) How can I make the legend match the lines too? Thank you.
Upvotes: 1
Views: 3473
Reputation: 5532
You can change the values vector in scale_colour_manual
as follows:
scale_colour_manual(values=c(mu = "blue", sd = "blue", Q1 = "red", Q3 = "red"))
This way, order won't matter.
The full ggplot
command would be:
ggplot(data=dat2 , aes(x=x, y=Value, group = Metric,colour = Metric)) +
geom_line() + geom_point() + ylab("value") +
xlab("v") +
scale_x_discrete(breaks = c( seq(1,5,1) ) ) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_y_continuous(breaks = c( seq(-3,3,.25) ) ) +
scale_colour_manual(values=c(mu = "blue", sd = "blue", Q1 = "red", Q3 = "red")) +
facet_wrap(~ group, ncol=3)
Upvotes: 2