Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

r - Assign Colour to each line in ggplot2

Hello People, I am trying to use the geom_line function to create line graphs in R. I want to assign specific colours to each line and I am unable to do so. When I try to manually assign the colours I get the colour names as variables and in the legend they get arranged alphabetically. If I don't then I don't get any colours at all. I also looked around on the web and noticed that there should be a grouping variable by which colours can be assigned. Unfortunately, in my dataset here, each column corresponds to a different variable. I am not sure transposing the dataset would work because I am trying to plot these variables against >2000 values on x-axis. I think I am missing something very simple here.

ggplot(data=data, aes(xvar))+
geom_line(aes(y=var1))+
geom_line(aes(y=var2))+
geom_line(aes(y=var3))+
geom_line(aes(y=var4))

enter image description here

Please feel free to redirect this to another section if this has been answered before. Any help would be greatly appreciated.

I am also able to do it manually without using the ggplot2 function the code for which is as follows:

plot(data$Wavelength,data$var1,col="green")
par(new=T)
plot(data$wavelength,data$var2,col="red")
par(new=T)
plot(data$wavelength,data$var3,col="purple")
par(new=T)
plot(data$wavelength,data$var4,col="black")
par(new=F)

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

here are some shortcuts that may be helpful:

dat <- data.frame(wave = 1:100,
                  var1 = sort(rnorm(100)),
                  var2 = sort(rnorm(100, 1)),
                  var3 = sort(rnorm(100, 2)))

plot(dat$var3, col = 'blue', type = 'l')
lines(dat$var2, col = 'red')
lines(dat$var1, col = 'green')

enter image description here

library(reshape2)
library(ggplot2)

dat.m <- melt(dat, id.vars = 'wave')

ggplot(dat.m, aes(wave, value, colour = variable)) + geom_line()

enter image description here

ggplot(dat.m, aes(wave, value, colour = variable)) + geom_line() + 
  scale_colour_manual(values = c('pink','orange','white'))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...