Reputation: 21
I have multiple lines to plot and and I whish to group in 3 categories the data. Please find here a reproductible example :
x <- c(1:20, 1:20,1:20,1:20,1:20,1:20,1:20)
variable <- c(rep("y1", 20), rep("y2", 20),rep("y3", 20),rep("y4", 20),rep("y5", 20),rep("y6", 20),rep("y7", 20))
value <- c(rnorm(20), rnorm(20,1),rnorm(20,2),rnorm(20,3),rnorm(20,5),rnorm(20,6),rnorm(20,7))
type=c(rep("A",100),rep("B",40))
df <- data.frame(x, variable, value,type)
library(ggplot2)
d <- ggplot(df, aes(x=x, y=value, group=variable, colour=type)) + geom_line(size=0.5,alpha=0.6)+
geom_line(data=subset(df,variable=="y6"),size=2,alpha=1,col="blue")+
geom_line(data=subset(df,variable=="y7"),size=2,alpha=1,col="black")
I expected 3 categories in the legend plot : "A" group in thin red line, "y6" group in blue, "y7" in black and thicks lines. How could I correctly set the legend ?
many thanks for your help, ochees
Upvotes: 0
Views: 830
Reputation: 21
Thank you s_t for your answer. However, I can not apply this method to my dataset.
Please find my dataset
set.seed(123)
ZS=c(rep(0,4),rep(300,4),rep(600,4),rep(900,4),rep(1200,4),rep(1500,4),rep(1800,4),rep(2100,4),rep(2400,4),rep(2700,4),rep(3000,4))
MEAN=c(21+rnorm(4),19+rnorm(4),17+rnorm(4),15+rnorm(4),13+rnorm(4),12+rnorm(4),13+rnorm(4),9+rnorm(4),6+rnorm(4),5+rnorm(4),1+rnorm(4))
Model_short=c(rep(c("mod3","mod4","obs1","obs2"),11))
color=c(rep(c("r","r","ref1","ref2"),11))
size=c(rep(c(0.5,0.5,1,1),11))
alpha=c(rep(c(0.5,0.5,1,1),11))
data=data.frame(
ZS=ZS,
MEAN=MEAN,
Model_short=Model_short,
color=color,
size=size,
alpha=alpha)
and script here :
library(ggplot2)
myColors=c("#4CA54C","#000000","#717171")
names(myColors) <- levels(data$color)
colScale <- scale_colour_manual(name = "grp",values = myColors)
p<-ggplot(data,aes(x = ZS,y=MEAN,group=Model_short,color=color)) +
geom_line(size=data$size,alpha=data$alpha)+
theme_bw()+theme(legend.position = "right")+
ylab("ylab")+
xlab("xlab")+
coord_flip()+ggtitle("title")+colScale
print(p)
Thank you very much
Upvotes: 0
Reputation: 9505
Welcome to SO! What about work on your data instead of working on ggplot
(remember to put a set.seed(123)
to make your data reproducible also in for other people):
# define the colors
df$color <- ifelse(df$variable == 'y6', 'A',ifelse(df$variable == 'y7', 'B','C'))
# define the size of the lines
df$size <- ifelse(df$variable %in% c('y6','y7'),2,0.5)
# here a custom palette of colors
myColors <-c("black","blue","red")
names(myColors) <- levels(df$color)
colScale <- scale_colour_manual(name = "grp",values = myColors)
# here the plot, adding your color palette, and the columns created
library(ggplot2)
ggplot(df, aes(x=x, y=value, group=variable,color=color)) +
geom_line(size= df$size,alpha=1) +
colScale
Upvotes: 2