R语言绘制按GaPa_NaPa分组的Forest.Area.ha.饼图方法
R绘制按行政区分组的森林面积饼图

现有数据结构
你提供的数据框结构如下:
structure(list(GaPa_NaPa = c("Gaidahawa", "Kanchan", "Kotahimai", "Marchawari", "Mayadevi", "Omsatiya", "Rohini", "Sammarimai", "Siyari", "Sudhdhodhan", "Devdaha", "Lumbini Sanskritik", "Sainamaina", "Siddharthanagar", "Tillotama", "Butwal"), Total.Area..ha. = c(9657L, 5835L, 5812L, 4844L, 7228L, 4844L, 6449L, 5066L, 6620L, 5743L, 13667L, 11194L, 16082L, 3595L, 12592L, 10139L), Forest.Area.ha. = c(114.91, 178.19, 31.37, 43.43, 152.87, 29.12, 63.16, 59.81, 36.4, 16.42, 113.13, 422.87, 186.13, 167.2, 60.27, 45.3), Forest.Percent = c(6.67, 10.35, 1.83, 2.52, 8.88, 1.69, 3.67, 3.47, 2.11, 0.95, 6.57, 24.57, 10.81, 9.71, 3.5, 2.63), Forest.Area..Fraction. = c(0.07, 0.1, 0.02, 0.03, 0.09, 0.02, 0.04, 0.03, 0.02, 0.01, 0.07, 0.25, 0.11, 0.1, 0.04, 0.03), Household.No = c(8612L, 9828L, 5939L, 5305L, 8003L, 6683L, 6349L, 5164L, 7889L, 7619L, 15624L, 10736L, 17572L, 12329L, 30452L, 36989L), Family.Size = c(10020L, 10483L, 7921L, 6972L, 10040L, 8218L, 8096L, 7303L, 9060L, 8717L, 17582L, 13854L, 19657L, 16011L, 36399L, 51099L), Total = c(56529L, 42528L, 46417L, 41058L, 57341L, 41080L, 43277L, 43300L, 45274L, 41472L, 71806L, 88090L, 78477L, 76307L, 149657L, 195054L)), row.names = c(NA, 16L), class = "data.frame")
原有代码问题
你写的代码有两个核心错误,导致无法出图:
pie()函数第一个参数必须传入数值型向量定义每个扇区的大小,你传入了字符型的行政区名称列GaPa_NaPa,无法计算扇区占比- 读入数据时赋值的对象名是
ForestArea2010,调用时却写了不存在的RupandehiLULC19,对象名不匹配会直接抛出错误
原有错误代码:
setwd("C:/Users/lenovo/Desktop/AllAboutR/AssignmentDocs") ForestArea2010<-read.csv("Forest2010.csv") View(ForestArea2010) pie(RupandehiLULC19$GaPa_NaPa, main="Piechart of Forest Area", las=3, col=hsv(12))
正确实现代码
基础R原生函数实现
# 设置工作路径 setwd("C:/Users/lenovo/Desktop/AllAboutR/AssignmentDocs") # 读入数据 ForestArea2010 <- read.csv("Forest2010.csv") # 生成扇区标签:行政区名+森林面积占比 pie_labels <- paste0( ForestArea2010$GaPa_NaPa, "\n", round(ForestArea2010$Forest.Area.ha. / sum(ForestArea2010$Forest.Area.ha.) * 100, 1), "%" ) # 绘制饼图 pie( x = ForestArea2010$Forest.Area.ha., labels = pie_labels, main = "各行政区森林面积占比(单位:公顷)", col = rainbow(nrow(ForestArea2010)), border = "white" )
行政区数量较多时,原生
pie()函数的标签容易重叠,更推荐用ggplot2绘制可读性更高的版本。
ggplot2版本实现(推荐)
如果未安装ggplot2,先运行install.packages("ggplot2")完成安装,再执行以下代码:
library(ggplot2) ggplot(ForestArea2010, aes(x = "", y = Forest.Area.ha., fill = GaPa_NaPa)) + geom_col(color = "white", linewidth = 0.5) + # 转换为极坐标生成饼图 coord_polar(theta = "y", start = 0) + # 添加扇区占比标签 geom_text( aes(label = paste0(round(Forest.Area.ha./sum(Forest.Area.ha.)*100, 1), "%")), position = position_stack(vjust = 0.5), size = 3 ) + # 设置图表标注 labs( title = "各行政区森林面积占比(单位:公顷)", fill = "行政区", x = NULL, y = NULL ) + theme_bw() + # 清理冗余坐标轴元素 theme( axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank() )
内容的提问来源于stack exchange,提问作者Prabhakar
相关产品推荐
相关产品推荐

