barplot中的传说看起来不正确

时间:2012-12-18 15:29:49

标签: r

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)", 
names.arg=c("Spanish", "Speak" , "English","Speak", "Hindi", 
"Speak", "Arabic", "Speak",  "Body Lang", "Speak"), ylab="Skill level ", 
xlab="Language starting with mostly used", col=c("darkblue","red"),
cex.names=0.7,space=c(2,0,2,0,2,0,2,0,2,0))

legend("top",  c("darkblue","red"), c("reading/Writing", "Speaking")  );

蓝色用于“读/写”,红色用于“说”。如何在图例中进行修正? (我不想在barplot函数中定义图例)

enter image description here

2 个答案:

答案 0 :(得分:24)

您可以使用fill参数作为颜色。与David Robinson的回答一样,我也建议在这种情况下将图例放在右上角。

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

enter image description here


在查看您的其他一些问题时,您可能还需要花一些时间在绘图之前将数据转换为更合适的形式。

以下是一个例子:

  1. 以下是您的数据:

    heights1 = c(5, 5, 4.5, 4, 4, 4, 4.5, 2, 4, 4) # Your data
    
  2. 以下数据为matrix,且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. 定义您的颜色(可选,但如果您每组不仅仅使用一对条形图,则非常有用)

    colors <- c("darkblue", "red") # Define the colors you're using
    
  4. 绘制数据,在顶部添加一点额外空间并抑制轴。不确定为什么你不想在这个阶段包含图例,但可以通过添加以下参数轻松完成: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. 重新引入您的y轴并添加您的图例

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

    enter image description here

答案 1 :(得分:3)

legend行更改为

legend("topright", c("reading/Writing", "Speaking"), col=c("darkblue","red"), lwd=10);

lwd参数表示图例应具有每个相应颜色的10像素厚度的线条。在你的情况下使用"topright"而不是"top"是个好主意,这样传说就不会出现在条形图下面。

enter image description here