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

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top