1

For months I've been trying to figure out how to solve this problem. Always when I want to plot a legend, the legend seem to appear at the bottom of the plot.

Here is my data:

weight <- data.frame(c("Ben", "Tom", "Toni", "Clive", "Alex"), 
                     c(72, 65, 87, 75,77), 
                     c("m", "m", "f", "m", "f"))
colnames(weight) <- c("Name", "Weight", "Gender")

Now I generate the plot:

plot(sort(weight$Weight, decreasing = T), type = "h",
     col = ifelse(weight$Gender == "f",'red','green'),
     pch = 19, xaxt = "n")
axis(side=1, at=1:5, labels=weight$Name)

Here you can see the plot before inserting the legend Here you can see the plot before inserting the legend

Now I generate the legend:

legend("topright", legend=c("male", "female"),
       fill=c("red", "green"), lty=1:2)

Here you can see the plot with the legend:

Here you can see the plot with the legend:

Why does this happen?

EcologyTom
  • 2,344
  • 2
  • 27
  • 38
BeneGIS
  • 13
  • 6
  • 3
    I can't reproduce this, for me the legend appears as expected. Maybe try again in a fresh R session? – kath Aug 15 '18 at 14:23
  • I also can't reproduce it. – Anonymous coward Aug 15 '18 at 14:25
  • I coud not reproduce the bug either. Legend shows fine on the top right. Could be some left over from previous graphs settings. – R. Prost Aug 15 '18 at 14:26
  • I continue to have this problem since I am using R with all legends I have ever tried to produce. What might be the cause? – BeneGIS Aug 15 '18 at 14:29
  • Try to start a new R session – S Rivero Aug 15 '18 at 14:31
  • Do you use RStudio or plain R ? and which versions on what type of machine ? there has been issues in the past it seems. – R. Prost Aug 15 '18 at 14:45
  • I use version 1.0.143 of RStudio. Maybe I can try to load a newer version. Starting a new R session doesn't help. – BeneGIS Aug 15 '18 at 14:48
  • Try `dev.off()` to reset your graphics? – EcologyTom Aug 15 '18 at 15:33
  • 1
    Alternatively try [RStudio's recommendations](https://support.rstudio.com/hc/en-us/articles/200488548-Problem-with-Plots-or-Graphics-Device) for this sort of thing. – EcologyTom Aug 15 '18 at 15:55
  • Thanks @EcologyTom ! I just needed to change the plot region via "par(mar=c(2,2,2,2))" as stated in the recommendations. Now it works properly. – BeneGIS Aug 16 '18 at 09:22
  • See also this question's answer: https://stackoverflow.com/questions/39133170/how-to-reduce-the-size-of-the-legend-in-r-plot-while-still-making-it-readable – BeneGIS Sep 22 '20 at 09:00

0 Answers0