我有一个 10 行 2 列的矩阵,我想创建一个按行堆叠但按列堆叠的条形图。 这是我的矩阵代码
population_matrix<-matrix(c(filter_data$Rural.population,
filter_data$Urban.population),
nrow = 10,ncol = 2,byrow = FALSE)
这是条形图的代码
barplot(population_matrix/1000000,
xlab = "States",ylab = "Population (in Millions)",
col = c("Green","Blue"),
main = "Statewise population",
border = "Black")
我希望将每个州的农村人口和城市人口列堆叠起来,并按颜色区分。相反,农村人口堆积在一列,而城市人口堆积在另一列。
我相信你有这样的数据
# country rural urban
# 1 A 17 34
# 2 B 48 39
# 3 C 40 12
# ...
并且可以直接做:
barplot(t(dat[2:3]), ## or `dat[c('rural', 'urban')]`
xlab="States", ylab="Population (in Millions)",
col=3:4,
main="Statewise population",
border="Black",
names.arg=dat$country,
legend.text=c('rural', 'urban'))
数据:
dat <- structure(list(country = c("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J"), rural = c(46, 47, 20, 43, 35, 30, 39, 14, 36,
38), urban = c(27, 38, 47, 19, 27, 47, 49, 13, 28, 32)), class = "data.frame", row.names = c(NA,
-10L))