R语言绘制饼状图代码实例

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

R语⾔绘制饼状图代码实例
R编程语⾔有许多库来创建图表和图表。

饼图是将值表⽰为具有不同颜⾊的圆的切⽚。

切⽚被标记,并且对应于每个⽚的数字也在图表中表⽰。

在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()
当我们执⾏上⾯的代码,它产⽣以下结果 -
到此这篇关于R语⾔绘制饼状图代码实例的⽂章就介绍到这了,更多相关R语⾔饼状图内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

相关文档
最新文档