在R中使用ggplot2库堆积条形图

时间:2017-10-02 13:00:26

标签: r ggplot2 graph

DMU Name    trip    rate    time    sline   distan  wait    gate
Sadang      0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Jamsil      0.00    0.10    0.15    0.31    0.04    0.29    0.20 
Silim       0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Guro        0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Suwon       0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Suyu        0.06    0.26    0.21    0.23    0.12    0.34    0.30 

我有一个上面的数据,我想绘制一个堆积的条形图。

我试着这样做:

##graph
gr <- read.csv("graph.csv",header=TRUE, sep=",")

library(tidyr)
#convert into long format
df2<-gather(gr, key=Input,  value, -DMU.Name)

 library(ggplot2)


 ggplot(df2, aes(DMU.Name)) +geom_bar(aes(weight= value, fill = Input))+
 theme(axis.text.x = element_text(angle=60, hjust=1)) +
 scale_x_discrete(limits = c("Sadang","Jamsil","Silim","Guro Digital Complex",
 "Suwon","Sindorim","Suyu","Gangnam","Seoul Nat'l Univ.",
 "Yangjae","Bucheon","Gangbyeon","Seoul","Hongik Univ.","Bupyeong",
 "Yeongdeungpo","Sinchon","Samsung","Gasan Digital Complex","Konkuk University", 
 "Univ. of Education","Express Bus Terminal", "Seolleung", "Apgujeong","Gwanghwamun",
 "Hyehwa","Euljiro 1(il)-ga", "Yeonsinnae","Jonggak","Yeoksam","Chungmuro","Myeong-dong")) +
   scale_fill_discrete(limits = c ("trip","rate","time","sline","distan","wait","gate","lines","stops","allocation"))

但是,我想更改条形颜色集。

我该怎么做?

感谢enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个快速解决方案:

df<-read.table(header = TRUE, text=
"DMUName    trip    rate    time    sline   distan  wait    gate
Sadang      0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Jamsil      0.00    0.10    0.15    0.31    0.04    0.29    0.20 
Silim       0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Guro        0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Suwon       0.00    0.00    0.00    0.00    0.00    0.00    0.00 
Suyu        0.06    0.26    0.21    0.23    0.12    0.34    0.30")

library(tidyr)
#convert into long format
df2<-gather(df, key=Name,  value, -DMUName)

library(ggplot2)
#plot
g<-ggplot(df2, aes(DMUName)) +geom_bar(aes(weight= value, fill =Name))
print(g)