How I can modify this code to have different colors for lines (for example Black, red, green)
library(ggplot2)
lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
grp = factor(c(1, 1, 2, 2, 3, 3),
levels = 1:3,
labels = c("Group 1", "Group 2", "Group 3")))
ggplot(mtcars, aes(mpg, disp)) +
geom_point(aes(colour=factor(vs),
fill = factor(vs)), shape=21, size = 4) +
scale_fill_manual(values=c("blue", "pink")) +
scale_colour_manual(values=c("black", "black"))+
geom_hline(data = lt,
mapping = aes(yintercept = yint, linetype = grp))
I tried to use this function buT I got the error
ggplot(DataSet, aes(AGE, RESULT)) +
geom_point(aes(colour=PATIENT.SEX,
fill = PATIENT.SEX), shape=21, size = 1.4) +
scale_fill_manual(values=c("hotpink", "skyblue2")) +
scale_colour_manual(values=c("hotpink", "skyblue2"))+
ylab("Potassium (mmol/L) ")+xlab("Age (month) ")+ggtitle("Alberta observations")+theme_bw()+
theme(plot.title = element_text(lineheight=.8, face="bold",size=13))+
theme(axis.text=element_text(size=12),axis.title=element_text(size=12,face="bold"))+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))+
geom_hline(data = lt,
mapping = aes(yintercept = yint,linetype = RI),colour
=c("blue","blue", "red", "red", "black","black" ))
A solution is to modify the
scale_color_manual
call. Set thevalues
and thelimits
for the factor levels forvs
(as already done in your post) and for the three group levels. In the example below I've set the color for thefactor(vs)
to black for both levels, as was done in the original post, and then set the colors for Group 1, Group 2, and Group 3 as purple, green, and yellow.One "brute force" option available starting in the current development version of ggplot2, 2.2.1.9000, is to set colors outside of
aes
. The colors you give either has to be length 1 (all colors the same) or the same length as the dataset used in that layer.In your example you have 6 rows in your dataset to make 6 horizontal lines so I give 6 colors.
If using this method you have to be careful to get the colors matched up with the appropriate row in the dataset. In your real use case you could consider adding the colors to the dataset to keep organized.
If you want to put the colors on the
linetype
legend, you can useguide_legend
andoverride.aes
to set legend colors.