楼主: dabap
4407 0

[问答] ggplot绘柱状图,如何让y轴按照特定的顺序显示???比如如何让y轴中的大值在下方显示 [推广有奖]

  • 0关注
  • 0粉丝

大专生

46%

还不是VIP/贵宾

-

威望
0
论坛币
2 个
通用积分
0
学术水平
0 点
热心指数
0 点
信用等级
0 点
经验
928 点
帖子
17
精华
0
在线时间
63 小时
注册时间
2012-4-1
最后登录
2016-8-8

8论坛币
library(ggplot2)


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))

pos_max <- rep(0,9)

for (i in 1:9){
  pos_max[i]=max(raw_data[i,1:6])
}

sre <- sort(pos_max, index.return=TRUE)

sort_index <- sre$ix

type_name <- c('SO2','C0','N02','03_8h','PM10','PM2.5')

position <- c('奥体中心','草场门','迈皋桥','仙林大学城','浦口','瑞金路','山西路','玄武湖','中华门')

data <- 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[index] <- raw_data[i,j]
    type[index] <- type_name[j]
    pos[index] <- position[i]
  }
}

data_all <-  data.frame(
  data,
  type,
  pos
)

gp <- ggplot(data=data_all, aes(x=reorder(data_all$pos, data_all$data, max), y=data_all$data, fill=data_all$type)) + geom_bar(stat="identity")
for(i in 1:9){
  ik <- sort_index[i]
  for(j in 1:6){
    gp <- gp + annotate("text", x=i, y=sum(raw_data[ik,1:j])-raw_data[ik,j]/2, label=as.character(raw_data[ik,j]))
  }
}

gp



QQ图片20151028233358.png (21.96 KB)

QQ图片20151028233358.png

关键词:gplot plot 柱状图 GPL Library ggplot R 柱状图 堆叠图
您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-5-11 17:47