点击链接加入群【农产品一体化解决方案】:https://jq.qq.com/?_wv=1027&k=49BAREK
饼图是表示不同颜色的值的圆片,切片标记和对应于各切片的数量也被表示在图表中
R语言中的饼图使用pie()函数,接受正数作为一个向量输入来创建,附加参数用于控制标签,颜色,标题等
语法:
使用R创建一个饼图基本语法
pie(x,labels,radius,main,col,clockwise)
以下是所使用的参数的说明
- x - 是包含在饼图中使用的数值的矢量。
- labels - 用于给出切片的描述。
- radius - 指示饼图的圆的半径。(-1和+1之间的值)。
- main - 指示图表的标题。
- col - 指示调色板。
- clockwise - 是一个逻辑值指示该切片绘制顺时针或逆时针方向。
-
示例
只用了输入向量和标签创建了一个非常简单的饼图。下面的脚本将创建并保存饼图到R的当前工作目录。
-
# Create data for the graph. x <- c(21, 62, 10, 53) labels <- c("London", "New York", "Singapore", "Mumbai") # Give the chart file a name. png(file = "city.jpg") # Plot the chart. pie(x,labels) # Save the file. dev.off()
当我们上面的代码执行时,它产生以下结果:
饼图的标题和颜色
我们可以通过添加函数更多的参数扩展图表的特性。我们将使用参数 main 作为标题添加到图表,另一个参数是 col,将利用彩虹调色板在绘制的图表时。托板的长度应相同于图表值的数目。因此,我们使用 length(x)。
示例
下面的脚本将创建并保存饼图到R的当前工作目录。
# Create data for the graph. x <- c(21, 62, 10, 53) labels <- c("London", "New York", "Singapore", "Mumbai") # Give the chart file a name. png(file = "city_title_colours.jpg") # Plot the chart with title and rainbow color pallet. pie(x, labels, main="City pie chart", col=rainbow(length(x))) # Save the file. dev.off()
当我们上面的代码执行时,它产生以下结果:
切片百分比和图表图例
我们可以通过创建额外的图表变量添加切片百分比和图表图例。
# Create data for the graph. x <- c(21, 62, 10,53) labels <- c("London","New York","Singapore","Mumbai") piepercent<- round(100*x/sum(x), 1) # Give the chart file a name. png(file = "city_percentage_legends.jpg") # Plot the chart. pie(x, labels=piepercent, main="City pie chart",col=rainbow(length(x))) legend("topright", c("London","New York","Singapore","Mumbai"), cex=0.8, fill=rainbow(length(x))) # Save the file. dev.off()
当我们上面的代码执行时,它产生以下结果:
3D 饼形图
饼图和3个维度需要使用额外的软件包绘制。软件包:plotrix 称为 pie3D(一个函数,被用于此目的)。# Get the library. library(plotrix) # Create data for the graph. x <- c(21, 62, 10,53) lbl <- c("London","New York","Singapore","Mumbai") # Give the chart file a name. png(file = "3d_pie_chart.jpg") # Plot the chart. pie3D(x,labels=lbl,explode=0.1, main="Pie Chart of Countries ") # Save the file. dev.off()
当我们上面的代码执行时,它产生以下结果: