2013-08-20 46 views
1

我怎樣才能改變以下條形圖使:拆分條形圖

1)條之間沒有空格。 2)堆疊條的顏色應該看起來,如果較高的一個被較小的填充。

tim.seq<-seq(as.POSIXlt("2013-07-01 00:00:00",origin = "1960-01-01",tz="GMT"), 
      as.POSIXlt("2013-07-8 00:00:00",origin = "1960-01-01",tz="GMT"),by="1 day") 

library(ggplot2) 
times<-rep(tim.seq,2) 
key<-rep(LETTERS[1:2],each=length(times)/2) 
times<-c(times,times) 
key<-c(key,key) 
ref<-rep(LETTERS[1:2],each=length(times)/2) 
value<-to<-sample(1:20,length(times),T) 
df<-data.frame(times=times,key=key,ref=ref,value=value) 

p<-ggplot(df, aes(x=times)) 
p<-p + geom_bar(subset = .(ref =="A"), aes(y = value, fill = key), stat = "identity") 
p<-p + geom_bar(subset = .(ref =="B"), aes(y = -value, fill = key), stat = "identity") 
p<-p + geom_hline(yintercept = 0, colour = "grey90") 
p 
+1

我不明白你的第二點。 – csgillespie

+0

每個堆疊的酒吧都應該替換爲代表綠色和紅色酒吧的完整y數量的酒吧,代表紅色酒吧的小酒吧應該使用小酒吧,並且酒吧必須以小酒店的形式覆蓋高個子像水中的玻璃。 – Klaus

回答

1

看起來你不想堆疊條形,和你想的不同寬度的條代替。爲了讓您有不同的width參數和position="identity"

對於每一個時刻做實驗,你有4個不同的可能組合爲:key = {A或B}和Ref = {A或B}只是爲了說明這是如何你看,這裏有一個扔掉的圖形,你可以嘗試使用:

#create a new column to have Bar width be based on the Key 
df$w <- ifelse(key=="A", 5, 3) 

p <- ggplot(df, aes(x=times, y=value)) 
p <- p + geom_bar(data = subset(df, ref =="A"), aes(width=w*10000, fill=key), stat = "identity", position = "identity") 
p <- p + geom_bar(data = subset(df, ref =="B"), aes(width=w*5000, fill=key), colour="black", stat = "identity", position="identity") 

這將產生: enter image description here 但是,這肯定是不你想要什麼。這只是爲了說明你可以玩弄position =「identity」,position =「閃避」和各種寬度值。

創建彙總數據幀

在ggplot,你幾乎總是得到你想要處理的數據幀本身的東西。下面是與彙總數據的另一種嘗試持有的Y總量也增加了值時,裁判是產生「A」

library(plyr) 

#Create a summary data frame with y-value Totals 
new.df <- ddply(df, .(times), summarize, total=sum(value)) 

#add a column to sum up values when Ref is "A" 
ref.df <- ddply(df, .(times, ref), summarize, reftotal = sum(value)) 
new.df$reftotal <- ref.df$reftotal[ref.df$ref=="A"] #filter to the Ref value we are interested in 

p2 <- ggplot(new.df, aes(x=times)) 
p2 <- p2 + geom_bar(aes(y=total, width=50000), stat = "identity", position = "identity", fill="darkgreen") 
p2 <- p2 + geom_bar(aes(y=reftotal, width=30000), stat = "identity", position = "identity", fill="red") 
p2 <- p2 + geom_hline(yintercept = 0, colour = "blue") 
p2 

enter image description here

希望這可以讓你更接近你有什麼心神。