|
- library(ggplot2)
- library(plyr)
- library(grid)
- rm(list=ls())
- ##################
- #变量
- raw_data <- t(matrix(c(
- 31, 35, 86, 45, 106, 149,
- 35, 33, 88, 42, 101, 144,
- 28, 33, 78, 28, 107, 151,
- 34, 32, 96, 39, 113, 170,
- 31, 30, 70, 52, 100, 129,
- 50, 37, 94, 28, 108, 163,
- 36, 38, 82, 42, 109, 158,
- 35, 29, 81, 38, 102, 146,
- 35, 37, 86, 42, 105, 149
- ),6,9))
- type_name <- c('SO2','C0','N02','03_8h','PM10','PM2.5')
- position <- c('奥体中心','草场门','迈皋桥','仙林大学城','浦口','瑞金路','山西路','玄武湖','中华门')
- ################## IAQI排序
- b=sort(colSums(raw_data),index.return=TRUE,decreasing = TRUE)$ix
- my_color = c('orange','springgreen3','purple','blue','red','yellow')
- j<-1:6
- name_new <- type_name[b[j]]
- raw_data_1 = raw_data
- type_name1 = type_name
- for (i in 1:6){
- raw_data_1[,i] = raw_data[,b[i]]
- type_name1[i] = type_name[b[i]]
- }
- ###################
- #变量合并
- data_new <- rep(0,6*9)
- type <- rep("",6*9)
- pos <- rep("",6*9)
- for(i in 1:9){
- for(j in 1:6){
- index <- (i-1)*6+j
- data_new[index] <- raw_data_1[i,j]
- type[index] <- type_name1[j]
- pos[index] <- position[i]
- }
- }
- data_all <- data.frame(
- pos,
- type,
- data_new
- )
- ce<-ddply(data_all, "pos", transform, label_y = cumsum(data_new)-0.5*data_new)
- gp <- ggplot(ce, aes(x=reorder(pos,data_new, sum), y = data_new, fill = type)) +
- geom_bar(stat = "identity",width=0.7) +
- scale_fill_manual(values = my_color,breaks=name_new,labels=name_new)+
- geom_text(aes(y = label_y, label = data_new), vjust = 0.4, colour = "Black")+
- guides(fill=guide_legend(reverse = TRUE))+
- xlab("国控点位置")+ylab("Accumulation of IAQI")+
- theme_bw()+
- theme(
- plot.margin = unit(c(2,0.5,1,1),'lines'),
- axis.title.x = element_text(colour = 'black',size=15,face = 'bold',vjust=-0.5),
- axis.text.x = element_text(colour='black',size=10),
- axis.title.y = element_text(colour = 'black',size=15,face = 'bold',vjust=1.5),
- axis.text.y = element_text(colour='black',size=12)
- )
- print(gp)
复制代码 代码和图如上所示,目前输出为我所求,但有一个疑问就是颜色的顺序为什么和我想的不太一样。我认为颜色应该是按照我的设定,一个一个去填充,如先是orange,接着是springgreen3,purple这样,为什么其中的顺序变混掉了,是哪里出了问题?虽然最终程序实现,但这个问题还是困扰着我,希望各路大神能帮我解答,谢谢啦
|