我想从dd1生成如下图,仅使用基本R函数条形图,以便每个国家/地区按年份分组。我可以使用ggplot来做到这一点,但无法确定使用barplot让它工作的正确方法。
输入数据帧:
dd1< - data.frame(“yr”= c(2001,2002,2001,2002),“country”= c(“智利”,“中国”,“智利”,“中国”),“贸易”= c(1200,2400,2500,5000))
答案 0 :(得分:2)
只需使用 yr 和国家的tapply
将数据框转换为分组矩阵:
graph_data <- tapply(dd1$trade, list(dd1$yr, dd1$country), sum)
barplot(graph_data, beside=TRUE, col=rainbow(3),
legend=rownames(graph_data), ylim=c(0,30000000), ylab="Trade", xlab="Country")
使用随机数据展示亚洲国家的更大数据框:
asia_countries <- c("China", "India", "Indonesia", "Pakistan", "Bangladesh", "Japan", "Philippines", "Viet Nam",
"Iran", "Turkey", "Thailand", "Myanmar", "South Korea", "Iraq", "Afghanistan",
"Saudi Arabia", "Uzbekistan", "Malaysia", "Nepal", "Yemen", "North Korea",
"Sri Lanka", "Kazakhstan", "Syria", "Cambodia", "Azerbaijan", "Jordan",
"United Arab Emirates", "Tajikistan", "Israel", "Laos", "Kyrgyzstan", "Lebanon",
"Turkmenistan", "Singapore", "State of Palestine", "Oman", "Kuwait",
"Georgia", "Mongolia", "Armenia", "Qatar", "Bahrain", "Timor-Leste", "Cyprus",
"Bhutan", "Maldives", "Brunei")
set.seed(662018)
dd1 <- transform(expand.grid("yr" = c(2014:2016),
"country" = asia_countries),
"trade"= sample(2000:20000, 144, replace=TRUE))
graph_data <- tapply(dd1$trade, list(dd1$yr, dd1$country), sum)
# PASS LENGTH OF LEGEND SERIES (I.E. YEARS) INTO rainbow(n)
barplot(graph_data, beside=TRUE, col=rainbow(3), legend=rownames(graph_data),
ylim=c(0,20000), ylab="Trade", xlab="Country")