Legends r: Add legends to plots in R software : the easiest way! – Easy Guides – Wiki

Опубликовано: February 24, 2023 в 1:51 am

Автор:

Категории: Miscellaneous

Add legends to plots in R software : the easiest way! – Easy Guides – Wiki

  • R legend function
  • Title, text font and background color of the legend box
  • Border of the legend box
  • Specify legend position by keywords
    • Example 1: line plot
    • Example 2: box plot
  • Infos

The goal of this article is to show you how to add legends to plots using R statistical software.

To add legends to plots in R, the R legend() function can be used. A simplified format of the function is :

legend(x, y=NULL, legend, fill, col, bg)

  • x and y : the x and y co-ordinates to be used to position the legend
  • legend : the text of the legend
  • fill : colors to use for filling the boxes beside the legend text
  • col : colors of lines and points beside the legend text
  • bg : the background color for the legend box.

Example :

# Generate some data
x

To avoid repeating the above R code, we can create a custom plot function as follow :

makePlot

The arguments below can be used :

  • title: The title of the legend
  • text.font: an integer specifying the font style of the legend text; possible values are :
    • 1: normal
    • 2: bold
    • 3: italic
    • 4: bold and italic
  • bg: background color of the legend box
makePlot()
# Add a legend to the plot
legend(1, 95, legend=c("Line 1", "Line 2"),
       col=c("red", "blue"), lty=1:2, cex=0.8,
       title="Line types", text.font=4, bg='lightblue')

The arguments box.lty, box.lwd and box.col can be used to modify the line type, width and color for the legend box border, respectively.

# Remove legend border using box.lty = 0
makePlot()
legend(1, 95, legend=c("Line 1", "Line 2"),
       col=c("red", "blue"), lty=1:2, cex=0.8,
       box.lty=0)
# Change the border
makePlot()
legend(1, 95, legend=c("Line 1", "Line 2"),
       col=c("red", "blue"), lty=1:2, cex=0.8,
       box.lty=2, box.lwd=2, box.col="green")

The position of the legend can be specified also using the following keywords : "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center".

The effect of using each of these keywords are shown in the figure below :

Example 1: line plot

#  Example 1: line plot
makePlot()
legend("topleft", legend=c("Line 1", "Line 2"),
       col=c("red", "blue"), lty=1:2, cex=0.8)

Example 2: box plot

attach(mtcars)
boxplot(mpg~cyl, 
        xlab="Cylinders", ylab="Miles/(US) gallon", 
        col=topo.colors(3))
   
legend("bottomleft", inset=.02, title="Number of Cylinders",
   c("4","6","8"), fill=topo. colors(3), horiz=TRUE, cex=0.8)

Note that the argument fill indicates the colors to use for filling the boxes beside the legend text

Enjoyed this article? I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter, Facebook or Linked In.

Show me some love with the like buttons below… Thank you and please don’t forget to share and comment below!!

Avez vous aimé cet article? Je vous serais très reconnaissant si vous aidiez à sa diffusion en l’envoyant par courriel à un ami ou en le partageant sur Twitter, Facebook ou Linked In.

Montrez-moi un peu d’amour avec les like ci-dessous … Merci et n’oubliez pas, s’il vous plaît, de partager et de commenter ci-dessous!

Add Legend to Plot in R

Improve Article

Save Article

  • Last Updated :
    16 May, 2021
  • Read
  • Discuss
  • Improve Article

    Save Article

    Legends are useful to add more information to the plots and enhance the user readability. It involves the creation of titles, indexes, placement of plot boxes in order to create a better understanding of the graphs plotted. The in-built R function legend() can be used to add legend to plot. 

    Syntax: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)

    Parameters:

    • x and y: These are co-ordinates to be used to position the legend
    • legend: Text of the legend
    • fill: Colors to use for filling the boxes of legend text
    • col: Colors of lines
    • bg: It defines background color for the legend box.
    • title: Legend title        (optional)
    • text.font: An integer specifying the font style of the legend (optional)

    Returns: Legend plot

    After normally visualizing our plot, to add legend to it only appropriate arguments with required values are to be given to the legend() function. 2

      

    plot(x, y, col="blue")

      

    lines(z, y ,col="red")

      

    legend(2, 4, legend=c("Equation 1", "Equation 2"), 

           fill = c("blue","red")

    )

    Output

    The legend box in the graph can be customized to suit the requirements in order to convey more information and add aesthetics to the graph at the same time. Given below are properties of legends basing which they can be customized:

    • title: The title of the legend box that can be declared to understand what the index of the indicates
    • position :  Indicator of the placement of the legend box ; which can have the possible options : “bottomright”, “bottom”, “bottomleft”, “left”, “topleft”, “top”, “topright”, “right” and “center”
    • bty (Default : o) : The type of box to enclose the legend . Different types of letters can be used, where the box shape is equivalent to the letter shape. For instance, “n” can be used for no box.
    • bg: A background colour can be assigned to the legend box
    • box.lwd : Indicator of the line width of the legend box
    • box.lty : Indicator of the line type of the legend box
    • box.col : Indicator of the line color of the legend box

    When appropriate values are applied to these properties, and they are then passed to the legend() function the required customization is achieved. 2

      

    plot(x, y, col="blue")

      

    lines(z, y ,col="red")

      

    legend(x = "topleft", box.col = "brown",

           bg ="yellow", box.lwd = 2 , title="EQUATIONS"

           legend=c("Equation 1", "Equation 2"), 

           fill = c("blue","red"))

    Output

    The text of the legend function can also be customized for better styling using the following properties:

    • text. font: A numerical value which is an indicator of the font style of the legend text. It has the following values :(1 – normal 2- bold, 3 – italic, 4 – bold and italic)
    • text.col : Which is used to indicate the color of the text used to write legend text
    • border (Default : black) : Indicator of the border color of the boxes inside the legend box
    • fill_color : colors used for filling boxes

    Example:

    R

    x<-20:1

    y=x

    z= x*(1/4)

      

    plot(x, y, lty = 4,col="blue")

      

    lines(y, z ,lty = 6,col="orange")

      

    legend(x = "topleft", lty = c(4,6), text. font = 4, 

           col= c("blue","orange"),text.col = "blue"

           legend=c("Equation 1", "Equation 2"))

    Output

    Next

    Change Legend Size in Base R Plot

    Related Articles

    550 rubles for a large sightseeing tour “Myths, legends and secrets of St. Petersburg” In January 2023 for MegaCoupon

    550 rubles. For a large sightseeing tour “Myths, Legends and Secrets of St. Petersburg”

    Similar promotions:

    • Leningrad region
    • Entertainment
    • Tourism
    • Excursions

    Condition Conditions

    show all conditions to hide the conditions

    9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9000 9 The company “Excursions of St. Petersburg” will open you a charming St. Petersburg from the other side! Fascinating bus tours will make you fall in love with the northern capital all over again. Tickets with generous discounts!

    Incredibly interesting excursions will introduce you to the legends of the city and reveal all its secrets. Romantic lights of the city at night and amazing stories that you won’t find anywhere else… Unique tours will appeal to both guests of St. Petersburg and residents of this legendary city.

    “Excursions of St. Petersburg” – spend time with interest and benefit!

    Popular promotions

    -33%

    2,137

    2 More details 137

    Bucharestskaya

    -50%

    3461

    Read more 3461

    Dostoevskaya and 2,

    -50%

    312

    Read more 312

    Moscow and another 12

    -50%

    1 874

    9000 9000

    The area of ​​the uprising and another area 1

    -50%

    1 50

    1 More 50

    Krestovsky Island

    -50%

    31

    More 31

    Pushkinskaya and more 1

    -62%

    221

    Read more 221

    Avtovo and another 1

    -50%

    1 117

    1 Read more 117

    Dostoevskaya and another 2

    -50%

    1 946

    1 more 946

    Ladoga

    -50%

    1 1022

    1 More details 1022

    Kupchino

    -54%

    1671

    More details 1671

    Kupchino

    -50%

    2 93

    9004 more details0004 663

    More details 663

    Admiralteyskaya and more 1

    Stories and legends about plants

    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

    A

    Adonis (Adonis)

    Adonis is a beautiful young man with whom the goddess of love Aphrodite fell in love (mutually). Love for a mortal or mortal is always a punishment, so it happened this time too…

    more

    Calamus marsh

    “Tatar grass” or “ugly cane” – strange names of one of the most deserved medicinal plants.

    details

    Aconite

    Aconite is a poisonous plant, according to legend, it grew from the saliva / foam of Cerberus – a terrible, three-headed hellish dog, which Hercules pacified and brought to Mycenae… flowers and useful fruits. There is a legend that the great-great-great-grandmother of modern Actinidia grew up in the Garden of Eden…

    more details

    Anemone

    Anemone is the closest relative of Adonis and belongs to the same family of Buttercups. In the legends, their fates are also connected…

    more

    Astilba

    There is no Greek legend about the beautiful Astilba, simply because she comes from East Asia and North America. But there is such a story…

    details

    Astra

    Asters are traditionally confused with Chinese callistefus. Firstly, they are close, and secondly, they are similar, but the aster, unlike callistefus, is a perennial plant. There are several legends about asters …

    more

    Astrantia

    An amazingly delicate plant, as if descended from the paintings of medieval masters. Those with subtle light, conditional landscape, Madonnas with babies and lilies. Something from Hans Memling. And the name matches – Astrantia…

    more

    B

    Badan (bergenia)

    A plant from the Saxifrage family – Chigir or Mongolian tea, Russian ginseng…

    more

    Periwinkle

    Many things are said about periwinkle, which is understandable – an evergreen, resistant, flexible plant with character. There are many legends, and all of them are sad, we don’t even know which one to choose. Maybe like this…

    more

    Buzulnik

    Rays of the sun in a shady garden…

    more

    B

    Vasilek

    Cornflower, if you don’t know – a centaur. In Latin it is Centaurea…

    details

    Lady’s slipper

    Lady’s slipper is not a plant for every garden. This is a real orchid, that is, a delight, a collectible item…

    details

    Loosestrife

    A legend-fairy tale about how the goblin played cards…

    more

    Veronica

    Veronica, it seems, not one of our gardens could manage. Veronika is definitely not a prima, but a lovely girl from the corps de ballet, able to gracefully shade and / or emphasize the splendor of other flowers…

    every corner, you are tormented to weed out. And there’s a story about Veronica, a sad tale…

    more

    Catchment (aquilegia)

    Catchment, or aquilegia, has many folk names, which speaks of the popularity of the plant, of tender love for it. Dove, eagle, slipper of elves, lion’s grass, grumpy woman’s grass..

    more

    Г

    Carnation

    Everyone knows carnations. In Soviet times, red carnations were almost the only thing you could buy in flower shops. ..

    more

    Gelenium

    Gelenium is our guide from summer to autumn. The Greeks associated its appearance with the beginning of the Trojan War…

    details

    Geranium

    Geranium is probably known to everyone without exception. But, as usual, not the one we are talking about…

    details

    Hyacinth

    The legend of the hyacinth, like many Greek legends, is beautiful, but bloody – the ancient Greeks are such ancient Greeks.
    Hyacinth – the flower of rain and sadness…

    more

    Hydrangea

    There are many stories and legends about hydrangea. And what is true and what is not, you can no longer make out. Today let’s remember a real historical figure, to whom the hydrangea owes its spread in Europe…

    more

    D

    Delphinium

    Delphiniums in the flower garden stand out with royalty and grandeur, make you turn around more than once…

    more

    Loosestrife

    Loosestrife is good everywhere – in a rose garden, in a natural-style flower garden, and by the water. There are many legends about him, one is better than the other, but almost all of them are connected with moisture droplets that the leaves of the plakun-grass secrete …

    more

    Dicentra

    A broken heart (that is, an exceptional or excellent dicentra) is an ephemeroid, and legends, of course, are all about it…

    more

    Oregano

    A fragrant pantry of health with an interesting history. The Greeks believed that Zeus, when he was a baby, was fed with honey, which bees collected from oregano flowers…

    more

    F

    Jasmine

    Fragrant creeper from warm countries

    details

    Honeysuckle

    Honeysuckle, unlike all other vines, twists counterclockwise around the support. They say that this is due to the extremely stubborn nature of the girl, who did everything in defiance…

    more

    And

    Iris

    Iris got its name in honor of the rainbow goddess Irida. There are a lot of legends about him. ..

    more

    K

    Kizil

    How Satan deceived himself!

    more

    Clematis

    Absolutely unpretentious, grateful, durable, very correct plant for the garden. And we’ll tell you about something else – about how clematis learned to climb…

    details

    Black cohosh

    Black cohosh are stately handsome men with a dissonant name. However, in the German tradition, black cohosh has a much more elegant name: “silver candles”…

    details

    Bell

    Bells are very different, but they are all equally charming. There is something unimaginably touching in them…

    more

    Kosmeya

    Kosmeya and Cosmos – a legend about love

    more

    Kotovnik

    Kotovnik – “catnip” – a plant dedicated in ancient Egypt to the goddess Bast (Bastet). Bast is a catwoman, the goddess of the moon, childbirth and fertility, hearth, dance, fun and joy. .. and its name reflects the hemostatic properties of a decoction of the roots of the plant, although …

    more

    Crocus

    This flower has two names and a history going back centuries. The crocus symbolizes hope and rebirth, as the crocus blooms even in the snow. In the language of flowers, it is a symbol of happiness, fun and joy…

    more

    Swimsuit

    In the Scandinavian tradition, the bathing suit is a troll’s flower, given to him to protect him from various misfortunes…

    more

    Kupena

    They say that the wise King Solomon specially marked the healing bath with his seal ring, so that if necessary it could be easily found among others…

    more

    L

    Meadowsweet (meadowsweet)

    Meadowsweet, or meadowsweet – foam that fell from the beautiful body of Aphrodite at the moment when the goddess first came out of the sea onto land… . These are the drops of sweat of the goddess Diana, who was running away from the Faun seized with passion, and the tears of the sea princess Volkhova, yearning for Sadko, and the treasures of the elves. ..

    more

    Daylily

    Daylily is a flower of joy and sadness. There are not as many legends about it as about lilies (or maybe they were simply not distinguished, who knows), but still there are several … . Optional: lily – tears of Eve expelled from Paradise; Hera’s milk; magic wand of Oberon…

    more

    Chinese Schisandra

    Schisandra has been known in China since the 15th century for its healing properties…

    more

    M

    Manzhetka

    The Russian name “manzhetka” is due to the appearance of the leaves. named after the Spanish physician Nicola Monardes…

    more

    P

    Peony “Henry Boxtos”

    Variety history…

    more

    Peony “Sarah Bernhardt”

    A peony named after one of the brightest women of the century. She was called “the most famous actress in history.” She conquered the hearts of Mark Twain, Victor Hugo, Marcel Proust, Alexander Dumas and Pyotr Ilyich Tchaikovsky, almost all the monarchs of Europe bowed before her talent. ..

    more

    Peony. Greek legend

    Ancient Greek legend about the wonderful helper of Asclepius…

    more

    Peony. Ito hybrids

    ITO peonies were obtained by crossing herbaceous and tree peonies and retained the best qualities of their “parents”.

    more

    Peony. Chinese legend

    An old Chinese legend about the Garden of a Hundred Flowers…

    more

    Primula

    Primula is called the Keys to Paradise, and all because once St. Peter..

    more

    R

    Rose

    The story goes like this: the Indian goddess of love and beauty was born from a rose bud. Vishnu saw her sleeping in a wonderful fragrant cradle, woke her up with a kiss and made her his wife…

    Read more

    Rose “Abraham Darby”

    History about hard work, success and continuity …

    Read more

    Rose “All the Rage”

    American dream of the originator Lima …

    rose rose rose rose “Aspirin Rose”

    Rose dedicated to the 100th anniversary of the famous drug. ..

    details

    Rose “Dame Judi Dench”

    Dedication to the beautiful British actress Judi Dench.

    more

    “Darcey Bussell” rose

    David Austin’s beautiful rose – a recognition of the talent and beauty of Covent Garden prima ballerina Darcy Bussell…

    more

    “Emily Bronte” rose

    more

    Rose “Emily Carr”

    Rose dedicated to the Canadian artist Emily Carr, who painted nature paintings of her native country and artistic sketches of the history and culture of the Indian tribes of the Canadian coast. ..

    more

    Rose “Gebruder Grimm”

    A magnificent floribunda dedicated to the memory of the great storytellers. ..

    more

    Rose “Imperatrice Farah”

    Rose dedicated to the Shahban of Iran

    more

    Rose “La Chartreuse de Parme”

    A beautiful dedication to Stendhal’s immortal novel…

    more

    Rose “Lady of Shalott” – 1

    A beautiful rose with a story originating in King Arthur’s Chronicles. ..

    more

    rose “Lady of Shalott” of Shalott” – 2

    The second part of the story about the Lady of Shalot based on the works of Alfred Tennyson..

    more

    Rose “Leonardo da Vinci”

    Rose dedicated to the great artist, inventor, thinker, genius of the Renaissance…

    more details

    “Munsted Wood” rose

    A rose commemorating the personal estate of landscape architect Gertrude Jekyll…

    more details

    “Navy Lady” rose

    A rose dedicated to women in the Canadian Armed Forces 9005…

    more

    Rose “Novalis”

    Rose – a dedication to the German natural philosopher, writer and romantic poet Baron Georg Friedrich Philipp von Hunderberg…

    more

    Rose “Paul Bocuse”

    Paul Bocuse is the man who introduced the profession of a cook to the world, making it recognized and prestigious, and French cuisine a world heritage.

    more details

    “Pierre Arditi” rose

    A magnificent hybrid tea rose of the Meilland selection from the “Meilland Romance” series is dedicated to two outstanding men at once. ..

    more details

    9000 dedication4 Rose “Rhapsody4 Rose “05 in Blue” 9000 Blues Rhapsodies by George Gershwin

    more

    Rose “Roald Dahl”

    Rose dedication to a children’s book author…

    more

    Rose “Teasing Georgia”

    Romantic story of one love…

    more

    Rose “The Alnwick”

    Rose “The Alnwick” Alnwick Castle is located in the north of England in the county of Northumberland near the southern borders of Scotland, it is the main residence of the Duke of Northumberland…

    more

    Blue for You rose

    The rose is a dedication to the album of the British band Status Quo

    details

    Rose Augusta Luise

    Rose dedication to Countess Augusta Luise zu Stolberg-Stolberg

    details

    Meidiland roses

    There are famous dynasties where family members are successively engaged in a common cause. This is exactly the story of the French kennel Meillant, which began more than 150 years ago.

    more details

    Rudbeckia

    Rudbeckia – gold of the Dwarves…

    more details

    From

    Mackerel

    Mackerel or wig tree – an infrequent guest in the gardens of the North-West…

    more

    Т

    Thyme / thyme

    Thyme, also known as thyme, savory, Bogorodskaya grass, upland pepper, verest, greed, swan, lemon odor, muhopal, incense, chubarka, chibrik and so on… I can’t remember all the names.

    details

    Yarrow

    This fragrant plant is very decorative, and one can talk about its healing properties for a very long time…

    more

    tulip

    The name tulip comes from the Persian word toliban, which means “turban”…

    more

    F

    Phlox

    The name of the plant comes from the Greek word φλόξ “floco”, which means “flame” in translation…

    more

    Х

    Winter horsetail

    Winter horsetail is one of the best plants for coastal zones.