【问题标题】:stacked bar graph with ggplot2 library in RR中带有ggplot2库的堆叠条形图
【发布时间】:2017-10-02 13:00:26
【问题描述】:
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

【问题讨论】:

  • 您能否提供一个可重现的示例以及更详细的问题描述?具体来说,您为什么希望在您提供的代码示例中堆叠任何内容?
  • 对于条形图,您需要指定 y 变量和 stat = "identity",或 stat = "count"

标签: r ggplot2 graph


【解决方案1】:

这是一个快速的解决方案:

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)

【讨论】: