如何结合情节和传奇?

时间:2012-02-20 18:14:33

标签: r plot legend

我正在尝试将图例附加到R中的情节中。 我尝试了以下代码(取自http://www.harding.edu/fmccown/r/

# Define cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)

# Define some colors ideal for black & white print
colors <- c("white","grey70","grey90","grey50","black")

# Calculate the percentage for each day, rounded to one 
# decimal place
car_labels <- round(cars/sum(cars) * 100, 1)

# Concatenate a '%' char after each value
car_labels <- paste(car_labels, "%", sep="")

# Create a pie chart with defined heading and custom colors
# and labels
pie(cars, main="Cars", col=colors, labels=car_labels,
   cex=0.8)

# Create a legend at the right   
legend(1.5, 0.5, c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, 
   fill=colors)

然而,这并不是很好。在馅饼(汽车,主要=“汽车”,col =颜色,标签= car_labels,cex = 0.8)行之后,情节显示没有图例:-) .......我在互联网上看到的每个例子似乎都有绘图功能后的图例功能所以看起来很奇怪..............

当我尝试执行图例功能时,我得到了

  

传奇(1.5,0.5,c(“星期一”,“星期二”,“星期三”,“星期四”,“星期五”),cex = 0.8,   + fill = colors)   strwidth错误(图例,单位=“用户”,cex = cex):     plot.new还没有被调用

2 个答案:

答案 0 :(得分:5)

你离开了坐标系。试试这个

# Create a legend at the right   
legend("topleft", c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, fill=colors)

生成下面的图表:

pie chart

有关不同的展示位置选项,请参阅legend的帮助页面。

答案 1 :(得分:1)

我认为位置1.5, 0.5会将其排除在页面之外。尝试

legend("right", c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, fill=colors)

pie功能后,它显示没有图例; legend功能将图例添加到当前图表中。

PS。您也可以考虑其他类型的情节。饼图因视觉上的误导而臭名昭着。