r - 如何结合情节和传说?

标签 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)

然而,这并不能很好地工作。在 pie(cars, main="Cars", col=colors, labels=car_labels,cex=0.8) 行之后,显示的图没有图例:-) ......我在网上看到的每一个例子好像在plotting函数之后都有legend函数所以看起来很奇怪......

当我尝试执行我得到的图例函数时

legend(1.5, 0.5, c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, + fill=colors) Error in strwidth(legend, units = "user", cex = cex) : plot.new has not been called yet

最佳答案

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

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

生成下面的图表:

pie chart

有关不同的放置选项,请参阅图例 的帮助页面。

关于r - 如何结合情节和传说?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9366229/

相关文章:

matlab - 为什么缩放标记会改变位置?

r - 将杜威和卢路径分析结果绘制为 R 中的路径图

Python - 基于值绘制网格

r - ggplot2:如何按颜色将图例拆分为自定义图例

r - 将关键图例添加到 R 中的多直方图

r - 使用data.table时如何避免奇怪的变音错误

r - 从 R 发送电子邮件 - 当 Windows 中的计划脚本失败时

r - ggplot2:带有映射到两个分类变量组合的颜色和文本标签的箱线图

r - 在带有刻面的图形上添加 R^2

r - 当一个变量实际上是两列时 expand.grid