r - 如何使用三列在 R 中制作堆叠条形图,我想使用 barplot() 函数
问题描述
我想要 R 中的堆叠条形图,其中年份作为 x 轴,百分比作为 y 轴,土地使用作为颜色填充。我的数据如下
Year Percentage LandUse
1 2015 49.8 Agriculture
2 2012 51.2 Agriculture
3 2009 50.2 Agriculture
10 2015 22.5 fishing
11 2012 21.4 fishing
12 2009 21.9 fishing
19 2015 14.7 services and residential
20 2012 16.0 services and residential
21 2009 17.1 services and residential
28 2015 0.8 mining and quarrying
29 2012 0.7 mining and quarrying
30 2009 0.7 mining and quarrying
37 2015 0.4 water and waste treatment
38 2012 0.5 water and waste treatment
39 2009 0.4 water and waste treatment
46 2015 0.8 Industry and Manufacturing
47 2012 0.8 Industry and Manufacturing
48 2009 0.9 Industry and Manufacturing
解决方案
您可以使用ggplot2
包来绘制堆积条形图。注意Year
变量应该是factor
类型。请看下面的代码:
df <- structure(list(Year = c(2015L, 2012L, 2009L, 2015L, 2012L, 2009L,
2015L, 2012L, 2009L, 2015L, 2012L, 2009L, 2015L, 2012L, 2009L,
2015L, 2012L, 2009L), Percentage = c(49.8, 51.2, 50.2, 22.5,
21.4, 21.9, 14.7, 16, 17.1, 0.8, 0.7, 0.7, 0.4, 0.5, 0.4, 0.8,
0.8, 0.9), LandUse = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 5L,
5L, 5L, 4L, 4L, 4L, 6L, 6L, 6L, 3L, 3L, 3L), .Label = c("Agriculture",
"fishing", "Industry_and_Manufacturing", "mining_and_quarrying",
"services_and_residential", "water_and_waste_treatment"), class = "factor")), class = "data.frame", row.names = c("1",
"2", "3", "10", "11", "12", "19", "20", "21", "28", "29", "30",
"37", "38", "39", "46", "47", "48"))
df$Year <- factor(df$Year)
library(ggplot2)
ggplot(df, aes(Year, Percentage, fill = LandUse)) +
geom_bar(stat = "identity")
输出:
PS如果你想使用barplot
,你需要通过绘制值矩阵创建、图例、颜色等(几十行代码)。ggplot2
默认给你。
推荐阅读
- reactjs - 如何在反应中向 Firebase REST API 发送 POST 请求
- python - Python & Google Sheets - 在第 5 行和第 3 列中查找元素
- c - 将 c 程序中的内存与 AVX 的外部程序集对齐
- python - 当我从文件中提取数据时尝试在 python 脚本中使用 read(\n) 时出现 TypeError
- mysql - MySQL Select with join & max 给出了意外的输出
- amazon-web-services - AWS Cloudwatch 警报在一起触发时如何工作?
- angular - 如何避免模板中的异步链?
- android - 为什么我的列表视图可以在颤动中滚动几个项目?
- kubernetes - Kubernetes: fsGroup has different impact on hostPath versus pvc and different impact on nfs versus cifs
- javascript - 如何从javascript数组中选择具有不同值的多个特定属性