I am fairly new to R and I have the following queries :
I am trying to generate a plot in R which has multiple lines (data series). Each of these lines is a category and I want it to have a unique color.
Currently my code is setup in this way :
First, I am creating an empty plot :
plot(1,type='n',xlim=c(1,10),ylim=c(0,max_y),xlab='ID', ylab='Frequency')
Then for each of my category, I am plotting lines in this empty plot using a "for" loop like so :
for (category in categories){ lines(data.frame.for.this.category, type='o', col=sample(rainbow(10)), lwd=2) }
There are 8 categories here, and so there are 8 lines produced in the plot. As you can see, I am trying to sample a color from the rainbows() function to generate a color for each line.
However, when the plot is generated, I find that there are multiple lines which have the same color. For instance, 3 of those 8 lines have green color.
How do I make each of these 8 lines have a unique color ?
Also, how do I reflect this uniqueness in the legend of the plot ? I was trying to lookup the legend()
function, however it was not clear which parameter I should use to reflect this unique color for each category ?
Any help or suggestions would be much appreciated.
In this method to create a ggplot with multiple lines, the user needs to first install and import the reshape2 package in the R console and call the melt() function with the required parameters to format the given data to long data form and then use the ggplot() function to plot the ggplot of the formatted data.
You can create a scatter plot in R with multiple variables, known as pairwise scatter plot or scatterplot matrix, with the pairs function. In addition, in case your dataset contains a factor variable, you can specify the variable in the col argument as follows to plot the groups with different color.
If your data is in wide format matplot
is made for this and often forgotten about:
dat <- matrix(runif(40,1,20),ncol=4) # make data matplot(dat, type = c("b"),pch=1,col = 1:4) #plot legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend
There is also the added bonus for those unfamiliar with things like ggplot
that most of the plotting paramters such as pch
etc. are the same using matplot()
as plot()
.
If you would like a ggplot2
solution, you can do this if you can shape your data to this format (see example below)
# dummy data set.seed(45) df <- data.frame(x=rep(1:5, 9), val=sample(1:100, 45), variable=rep(paste0("category", 1:9), each=5)) # plot ggplot(data = df, aes(x=x, y=val)) + geom_line(aes(colour=variable))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With