R 饼图
饼图
饼图是数据的圆形图形视图。
使用 pie() 函数来绘制饼图:
实例
# 创建饼图向量 x <- c(10,20,30,40) # 显示饼图 pie(x)
结果:
例子解释:
如您所见,饼图为向量中的每个值(在本例中为 10、20、30、40)绘制一个饼。
默认情况下,第一个饼的绘制从 x 轴开始并逆时针移动。
注意:每个饼的大小是通过将此值与其他所有值进行比较来确定的,使用的公式如下:
该值除以所有值的总和:x/sum(x)
起始角度
您可以使用 init.angle 参数更改饼图的起始角度。
init.angle 的值以度为单位定义角度,其中默认角度为 0。
实例
从 90 度开始绘制第一个饼:
# 创建饼图向量 x <- c(10,20,30,40) # 显示饼图并从 90 度开始绘制第一个饼 pie(x, init.angle = 90)
结果:
标签和标题
使用 label 参数为饼图添加标签,使用 main 参数添加标题:
实例
# 创建饼图向量
x <- c(10,20,30,40)
# 创建标签向量
mylabel <- c("Apples", "Bananas", "Cherries", "Dates")
# 显示带有标签的饼图
pie(x, label = mylabel, main = "Fruits")
结果:
颜色
您可以使用 col 参数为每个饼图添加颜色:
实例
# 创建颜色向量
colors <- c("blue", "yellow", "green", "black")
# 显示带有颜色的饼图
pie(x, label = mylabel, main = "Fruits", col = colors)
结果:
图例
要为每个饼图添加解释列表,请使用 legend() 函数:
实例
# 创建标签向量
mylabel <- c("Apples", "Bananas", "Cherries", "Dates")
# 创建颜色向量
colors <- c("blue", "yellow", "green", "black")
# 显示带有颜色的饼图
pie(x, label = mylabel, main = "Pie Chart", col = colors)
# 显示解释框
legend("bottomright", mylabel, fill = colors)
结果:
图例可以定位在以下位置:
bottomright(右下角)bottom(底部)bottomleft(左下角)left(左侧)topleft(左上角)top(顶部)topright(右上角)right(右侧)center(居中)