banner



How To Change Size Of Legend In R

A legend of a plot helps to understand which series or groups corresponds to each bar, line, box or observations, based on its blazon, color or both. In this tutorial you will learn how to add a fable to a plot in base R and how to customize it.

  • 1 The R legend() office
  • two R legend position, lines and make full
  • 3 Fable title
  • four Legend border and colors
  • five Change legend size
  • 6 Fable outside plot
  • vii Add together two legends in R
  • 8 Plot legend labels on plot lines
  • 9 Add more info into legend

The R legend() function

The legend part allows you to add a legend to a plot in base of operations R. The summarized syntax of the role with the most common arguments is described in the following cake:

          legend(x, y,   # Coordinates (x also accepts keywords)        legend, # Vector with the name of each group        fill,   # Creates boxes in the legend with the specified colors        col = par("col"), # Colour of lines or symbols        border = "black", # Fill box border color        lty, lwd,         # Line blazon and width        pch,              # Add pch symbols to legend lines or boxes        bty = "o",        # Box type (bty = "due north" removes the box)        bg = par("bg")    # Background colour of the fable        box.lwd = par("lwd"), # Legend box line width        box.lty = par("lty"), # Legend box line type        box.col = par("fg"),  # Legend box line colour        cex = 1,          # Legend size        horiz = False     # Horizontal (Truthful) or vertical (FALSE) legend        title = Aught      # Legend title )        

Recall that there are even more arguments y'all can utilize, but nosotros listed the most common, so blazon args(legend), ?legend or help(legend) for boosted information.

In the following sections we volition explicate how to customize the most common arguments of the part. In club to avert repeating code we will use the following part to plot two Bessel functions in R (J_0(ten) and J_2(x)):

          plotl <- function(...) {     x <- seq(0, 30, 0.01)     plot(besselJ(10, 0), col = 2, type = "50",          lwd = 2, ylab = "Jn(x)", xlab = "", ...)     lines(besselJ(ten, 2), col = iii, type = "l", lwd = 2, lty = two) }   plotl()        
Example plot of Bessel functions

The plots of this commodity have been created with a window of width and height of 4 inches (10.16 cm): windows(four, 4), unless otherwise is indicated. In case of using other sizes yous may need to fine-tune some arguments to get the same outputs.

R legend position, lines and fill

When adding a legend to a plot, there are ii main ways to modify the legend position with the R legend function.

On the one paw, y'all tin can gear up the argument ten to "top", "topleft", "topright", "bottom", "bottomleft", "bottomright", "left", "correct" or "eye". In this scenario yous don't have to set the statement y.

          plotl() legend(x = "topright",          # Position        fable = c("J0", "J2"),  # Fable texts        lty = c(ane, 2),           # Line types        col = c(2, iii),           # Line colors        lwd = 2)                 # Line width        
Adding a legend to a plot in R

On the other hand, you can use the arguments ten and y as coordinates to indicate where to draw the legend.

          plotl() legend(x = 1900, y = 0.8, # Coordinates        legend = c("J0", "J2"),        lty = c(i, two),        col = c(2, three),        lwd = 2)        
Change legend position in R

Nevertheless, you can besides change the distance from the margin, in instance that you lot don't want the legend to be in the margin, with the inset argument:

          plotl() legend("topright",   # Position        inset = 0.05, # Altitude from the margin as a fraction of the plot region        fable = c("J0", "J2"),        lty = c(1, 2),        col = c(2, three),        lwd = 2)        
Adjust margin distance of the legend in R

If the lines of the plot contain any symbols y'all tin can add them to the legend with the argument pch.

Note that if yous demand to add a legend to a bar plot, pie chart or box plot you lot can utilize the fill argument instead of setting lines.

          barplot(tabular array(mtcars$gear), col = 2:four)  fable("topright",        legend = c(three, four, 5),        fill = 2:iv,       # Color of the squares        edge = "blackness") # Colour of the border of the squares        
Bar plot in R with legend

If your plot have shading lines yous can also add together them to the legend with the density argument and change the angle on the lines with the angle argument of the role.

          barplot(table(mtcars$gear), col = two:four, density = 30, angle = 90)  legend("topright",        fable = c(3, iv, v),        fill = 2:4,        density = 30, # Shading lines density        angle = 90)   # Angle of the shading lines        
Shading lines fill in R

Legend title

In case you demand to add together a championship to the legend, in order to add together some description of the elements of the fable, you can use the title argument. Note that you can customize the colour of the text with the title.col argument and that y'all tin can make a horizontal adjustment of the title with the title.adj argument.

          plotl() legend("topright", legend = c("J0", "J2"),        championship = "Legend TITLE",  # Championship        championship.adj = 0.5,         # Horizontal adjustment of the title        title.col = "blue",      # Color of the title        lty = c(one, 2), col = c(2, three), lwd = two)        
R legend title customization

Note that the argument text.font allows yous to modify the font of the texts of your legend.

Fable edge and colors

By default, the legend is drawn within a blackness rectangle. Nonetheless, you can modify the type, width and color of the line of the rectangle with the box.lty, box.lwd and box.col arguments, respectively.

          plotl() legend(1500, 0.9,        legend = c("J0", "J2"),        box.lty = 2, # Line type of the box        box.lwd = ii, # Width of the line of the box        box.col = four, # Colour of the line of the box        lty = c(1, two),        col = c(2, 3),        lwd = ii)        
R legend border color

Yous tin also disable the border of the box setting the argument bty every bit "n". Note that an alternative is to set box.lty = 0.

          plotl() legend(1500, 0.9,        legend = c("J0", "J2"),        bty = "n", # Removes the legend box        lty = c(1, ii),        col = c(2, three),        lwd = ii)        
Remove legend box in R

In improver, if byt is different to "n" you tin can set the background color of the legend box. Notation that if you don't want to bear witness the line of the box you tin gear up information technology to the background color of the plot or the background color of the box or but ready box.lty = 0.

          plotl() fable("topright", inset = 0.05,        legend = c("J0", "J2"),        bg = rgb(1, 0, 0, alpha = 0.15), # Legend groundwork color        box.col = "white",        lty = c(ane, 2),        col = c(2, three),        lwd = 2)        
Change legend background color in R

Change legend size

In order to change the legend size in R you can brand use of the cex argument. Values bigger than 1 volition lead to a bigger legend and smaller to smaller legends than the default.

          plotl() legend("topright",        legend = c("J0", "J2"),        lty = c(1, ii),        col = c(2, 3),        cex = 1.five, # Change fable size        lwd = 2)        
Modify legend size in R

Legend outside plot

Sometimes, the representation covers all the area of the plot. In that case, it is a expert idea to move the fable outside the plot. For that purpose, you will demand to brand utilize of the par function, to change the margins of the plot, and the inset and xpd arguments as follows:

          # Make the window wider than taller windows(width = 4.5, tiptop = 4)  # Salve electric current graphical parameters opar <- par(no.readonly = True)  # Change the margins of the plot (the fourth is the right margin) par(mar = c(5, 5, 4, six))  plotl() legend(10 = "topright",        inset = c(-0.45, 0), # Yous will need to fine-melody the first                             # value depending on the windows size        legend = c("J0", "J2"),         lty = c(1, ii),        col = c(2, 3),        lwd = 2,        xpd = TRUE) # You need to specify this graphical parameter to                    # put the fable outside the plot  # Back to the default graphical parameters on.exit(par(opar))        
Legend next to plot in R

Recall that for plots of other sizes yous will need to fine-tune the margins and the inset to obtain the right plot.

An alternative is to put the legend under the plot. For that purpose you lot can gear up the margins, the inset statement and the position to the following:

          windows(width = 4, height = 4)  # Salvage current graphical parameters opar <- par(no.readonly = TRUE)  # Alter the margins of the plot (the first is the bottom margin) par(mar = c(six, iv.1, four.one, two.one))  plotl() legend(x = "bottom",        inset = c(0, -0.five), # You will demand to fine-tune the 2nd                            # value depending on the windows size        fable = c("J0", "J2"),         lty = c(i, 2),        col = c(ii, 3),        lwd = ii,        xpd = Truthful, # You lot need to specify this graphical parameter to add                    # the legend outside the plot expanse        horiz = Truthful) # Horizontal fable. You tin can also fix the number                      # of columns with the argument ncol                      # if horiz = Faux  # Dorsum to the default graphical parameters on.exit(par(opar))        
Horizontal legend under R plot

You tin add two or more legends to a plot, but running the legend office multiple times with unlike arguments. In the post-obit example we are going to add ii more Bessel functions and add together a new fable for them.

          plotl() lines(besselJ(seq(0, 30, 0.01), 3), col = 4, type = "l", lwd = 2, lty = 2) lines(besselJ(seq(0, thirty, 0.01), iv), col = v, type = "l", lwd = two, lty = 2)  fable("topright",        legend = c("J0", "J2"),        lty = c(1, two), col = c(two, 3), lwd = 2)  fable("top",        legend = c("J3", "J4"),        lty = two, col = c(4, 5), lwd = 2)        
Adding two R legends

Notation that y'all tin can too add more legends outside the plot, in case the legends doesn't fit inside the layout.

          # Make the window wider than taller windows(width = 4.v, height = four)  # Save the electric current graphic parameters opar <- par(no.readonly = Truthful) par(mar = c(5, five, 4, 6))  # Create the plot plotl() lines(besselJ(seq(0, thirty, 0.01), three), col = four, type = "l", lwd = 2, lty = 2) lines(besselJ(seq(0, 30, 0.01), four), col = 5, type = "50", lwd = 2, lty = 2)  # Add commencement fable fable(10 = "topright",        inset = c(-0.45, 0),        fable = c("J0", "J2"),         lty = c(1, five), col = c(2, three),        lwd = 2, xpd = Truthful )  # Add second legend legend(x = "right",        inset = c(-0.45, 0),        legend = c("J3", "J4"),         lty = 2, col = c(4, v),        lwd = 2, xpd = True )  # Restore original graphical parameters on.exit(par(opar))        
Two legends in R

Plot fable labels on plot lines

You lot can also add legends to a plot labelling each line. In case you have a plot with several lines y'all tin can add a fable near to each line to identify information technology. For that purpose, you can make use of the legend role as many times every bit the number of lines:

          plotl(xlim = c(0, 4000))  legend(2800, 0.05, fable = "J0", bty = "northward") fable(2800, 0.25, legend = "J2", bty = "northward")        
Legend labels on R plot lines

An alternative is to use the text function and specify the text and the position. E.thou. text(3500, -0.075, "J0").

Add together more info into legend

Finally, information technology is worth to mention that, if needed, you can add more data to a legend. For that purpose, you tin change the margins of the plot and add some text with the text part.

          # Window taller than wider windows(width = iv, peak = v.5)  # Save current graphical parameters opar <- par(no.readonly = Truthful)  # Margins of the plot (the get-go is the bottom margin) par(mar = c(12, 4.i, 4.1, 2.1))  # Plot plotl()  # Legend under the plot fable(x = "bottom",        inset = c(0, -0.5), # You volition need to fine-melody the                            # kickoff value depending on the windows size        legend = c("J0", "J2"),         lty = c(i, two),        col = c(2, 3),        lwd = 2,        xpd = True,   # Yous need to specify this to add                      # the fable to put the legend outside the plot        horiz = TRUE) # Horizontal legend. You tin as well set the number                      # of columns with the argument ncol if horiz = FALSE  # Adding additional information par(xpd = True) text(1500, -ane.v, "You tin can add additional information\northward well-nigh the plot or fable")  # Back to the default graphical parameters on.exit(par(opar))        
Plot with additional information in R

How To Change Size Of Legend In R,

Source: https://r-coder.com/add-legend-r/

Posted by: davisduct1971.blogspot.com

Related Posts

0 Response to "How To Change Size Of Legend In R"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel