pie图是一种非常糟糕的信息展示方式,一般不建议使用
从本期开始,系统分享R制作各类统计图表的代码模版,力求最简单的方法达到目的。
本次主角:饼图(pie chart)。
pie图是一种非常糟糕的信息展示方式,一般不建议使用,因为人眼擅长判断线性度量,而不擅长判断相对面积,条形图或点图是pie图的更优选择。
reference:
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.Cleveland, W. S. (1985) The Elements of Graphing Data. Wadsworth: Monterey, CA, USA.
pie图在R中实现方法有很多,本次分享base R的方法制作pie图。
base R的方法,即R自带功能,不需要额外安装其它package。
1.1 饼图-最简单饼图
pie(c(1, 2, 3, 4, 5) # 设置数据
)
1.2 饼图-扇区顺时针方向
pie(c(1, 2, 3, 4, 5),
clockwise = TRUE # 设置扇区按顺时针方向排列(TRUE),从90度开始
)
1.3 饼图-扇区逆时针方向
pie(c(1, 2, 3, 4, 5),
clockwise = FALSE # 设置扇区按逆时针方向排列(FALSE),从0度开始
)
1.4 饼图-扇区颜色
colormap_set <- c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73") # 定义颜色
pie(c(1, 2, 3, 4, 5),
col = colormap_set # 设置颜色
)
1.5 饼图-扇区标签
colormap_set <- c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73")
label_set <- sprintf("slice%s", LETTERS[1:5]) # 定义扇区标签
pie(c(1, 2, 3, 4, 5), col = colormap_set, labels = label_set # 设置扇区标签
)
1.6 饼图-扇区样本数
values <- c(1, 2, 3, 4, 5) # 定义数据
colormap_set <- c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73")label_set <- sprintf("slice%s", LETTERS[1:5]) # 定义各部分标签
proportions <- values # 定义各部分标签中的百分比
labels_with_proportion <- sprintf("%s: %s", label_set, proportions) # 拼接各部分标签,百分比
pie(values,
col = colormap_set, labels = labels_with_proportion # 各部分标签,百分比
)
1.7 饼图-扇区样本比例值(位于侧方)
values <- c(1, 2, 3, 4, 5) # 定义数据
colormap_set <- c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73")label_set <- sprintf("slice%s", LETTERS[1:5])
proportions <- values / sum(values) * 100 # 定义扇区样本数比例值
labels_with_proportion <- sprintf("%s (%.1f%%)", label_set, proportions) # 拼接扇区标签,本数比例值
pie(values,
col = colormap_set, labels = labels_with_proportion # 设置扇区标签,本数比例值
)
1.8 饼图-扇区样本比例值(位于内部)
values <- c(1, 2, 3, 4, 5)colormap_set <- c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73")
label_set <- sprintf("slice%s", LETTERS[1:5])
pie(values, col = colormap_set, labels = label_set)
# 计算扇区样本比例值的坐标
angles <- cumsum(c(0, values)) / sum(values) * 2 * pi
mid_angles <- (angles[-length(angles)] + angles[-1]) / 2
x <- 0.5 * cos(mid_angles)
y <- 0.5 * sin(mid_angles)
# 定义扇区样本比例值
proportions <- values / sum(values) * 100
labels_with_proportion <- sprintf("%.1f%%", proportions)
text(x, y,
labels = labels_with_proportion, # 设置扇区样本比例值
col = "black", cex = 1.2
)
1.9 饼图-图例替代标签
colormap_set <- c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73")
label_set <- sprintf("slice%s", LETTERS[1:5])
pie(c(1, 2, 3, 4, 5), col = colormap_set)
legend("topright", # 图例的位置可以切换
label_set, # 图例标签
cex = 0.8,
fill = colormap_set)
colormap_set <- c("#2C69B0", "#F02720", "#AC613C", "#6BA3D6", "#EA6B73")
label_set <- sprintf("slice%s", LETTERS[1:5])
pie(c(1, 2, 3, 4, 5), col = colormap_set)legend("topright",
label_set,
cex = 0.8,
fill = colormap_set,
ncol = 3) # 设置图例的列数为3
未完待续......
-END-
每类图表包含详细代码+详细代码注释,多达8000行代码,例如,
如何加入学习?
👇加入学习(收费,请备注:169)