Different Colors of Points and Lines in Base R Plot Legend
In this article, we are going to see how to plot different colors of points and lines in base R Programing Language.
Creating a dataset for demonstration:
Let’s see in the above code where ‘A’,’B’,’C’ are the names of a matrix with vector input inside c() consisting of values. It also contains the number of rows, i.e., and ‘ncol’ as two.
Plotting line and point on graph with different color
After creating the matrix, now we will plot the lines and points.
Syntax: plot(x, y, type = “l”, lty = 1)
lines(x, y, type = “l”, lty = 1)
- x, y: coordinate vectors of points to join
- type: character indicating the type of plotting. Allowed value is : “p” for points
- lty: line types. Line types can either be specified as an integer (0=blank, 1=solid (default), 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash) or as one of the character strings “blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, or “twodash”, where “blank” uses ‘invisible lines’ (i.e., does not draw them).
In this above graph, we have lines and points plotted. There is no specification which line represents what, In order to do that we’ll the legend function to give them the same labels.
Adding a legend
When adding a legend to a plot, there is the main way to modify the legend position. You can set the argument x to “top”, “topleft”, “topright”, “bottom”, “bottomleft”, “bottomright”, “left”, “right” or “center”, In this scenario you don’t have to set the argument y.
In the code below, after plotting the graph we now add a legend with pch=c(NA, NA) it means that the legend section did not show the ‘pch’ meaning the points symbol’s which we can vary from 1 to 25 as per the user’s choice.
Adding point symbols to the legend by overlapping
Now we will just overlap the legend, symbols, as we have observed previously, the lines, are visible line the legend instead of point symbols.
So what we will do, we will assign the values to “pch” which we can vary from 1 to 25 as per the user choice every number represents a point shape i.e. pch =1, which is an empty circle, pch = 19 (solid circle), pch = 21 (filled circle), etc.