Legends in barplot not appearing properly

前端 未结 2 2008
别跟我提以往
别跟我提以往 2021-02-07 04:38
heights1=c(5,5,4.5,4,4,4,4.5,2,4,4)

opar <- par(lwd = 0.3)

barplot(heights1,xlim=c(0,3), ylim=c(0,5),  width=0.1, 
main=\"Langauges(Verbal & Non-verbal)\", 
nam         


        
2条回答
  •  遥遥无期
    2021-02-07 04:58

    You can use the fill argument for your colors. As with David Robinson's answer, I would also suggest placing the legend in the top right in this case.

    legend("topright", 
           legend = c("reading/Writing", "Speaking"), 
           fill = c("darkblue", "red"))
    

    enter image description here


    Looking at some of your other questions, you might also want to spend some time getting your data into a more appropriate form before plotting.

    Here's an example:

    1. Here is your data:

      heights1 = c(5, 5, 4.5, 4, 4, 4, 4.5, 2, 4, 4) # Your data
      
    2. Here is your data as a matrix with appropriate dimnames

      mydata <- matrix(heights1, ncol = 2, byrow = TRUE,
                       dimnames = list(c("Spanish", "English", "Hindi", 
                                         "Arabic", "Body Lang"),
                                       c("Reading/Writing", "Speaking")))
      mydata # Much more meaningful to look at than a simple vector
      #           Reading/Writing Speaking
      # Spanish               5.0        5
      # English               4.5        4
      # Hindi                 4.0        4
      # Arabic                4.5        2
      # Body Lang             4.0        4
      
    3. Define your colors (optional, but useful if you are working with more than just a pair of bars per group)

      colors <- c("darkblue", "red") # Define the colors you're using
      
    4. Plot your data adding a little bit of extra space at the top and suppressing your axes. Not sure why you don't want to include the legend at this stage, but it could easily be done by adding the following arguments: legend.text = TRUE, args.legend = list(x = "topright", bty = "n")

      barplot(t(mydata), beside = TRUE, col = colors, 
              ylim = c(0, 6), axes = FALSE,
              xlab = "Language starting with mostly used",
              main = "Languages (Verbal & Non-verbal)")
      
    5. Reintroduce your y-axis and add your legend

      axis(2, at = 0:5, labels = 0:5)
      legend("topright", colnames(mydata), fill = colors, bty = "n")
      

      enter image description here

提交回复
热议问题