Changing line thickness
For this, the size attribute is used with a specific value. The changes will be reflected in the legend too.
Example:
R
library ( "ggplot2" ) function1<- function (x){x**2} function2<- function (x){x**3} function3<- function (x){x/2} function4<- function (x){2*(x**3)+(x**2)-(x/2)} df= data.frame (x=-2:2, values= c ( function1 (-2:2), function2 (-2:2), function3 (-2:2), function4 (-2:2)), fun= rep ( c ( "function1" , "function2" , "function3" , "function4" )) ) ggplot (df, aes (x,values,col=fun))+ geom_line (size=3) |
Output:
Adding Legend to Multiple Line Plots with ggplot in R
In this article, we are going to see how can we add a legend to multiple line plots with ggplot in the R programming language.
For a plot that contains more than one line plot, a legend is created by default if the col attribute is used. All the changes made in the appearance of the line plots will also reflect in the legend.
Syntax: ggplot(df, aes(x, y, col=”name of the column to differentiate on the basis of”))
Let us first visualize how the curve will appear as default.
Example: Default plot
R
library ( "ggplot2" ) function1<- function (x){x**2} function2<- function (x){x**3} function3<- function (x){x/2} function4<- function (x){2*(x**3)+(x**2)-(x/2)} df= data.frame (x=-2:2, values= c ( function1 (-2:2), function2 (-2:2), function3 (-2:2), function4 (-2:2)), fun= rep ( c ( "function1" , "function2" , "function3" , "function4" )) ) ggplot (df, aes (x,values,col=fun))+ geom_line () |
Output:
Various changes made to the lines will appear in the legends as well, let’s see how:
Contact Us