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
4

1 回答 1

1

看起来您不想要堆叠条,而是想要不同宽度的条。要做到这一点,您必须尝试不同的width参数和position="identity"

对于每个时间瞬间,您有 4 种不同的可能组合: key = {A or B} 和 Ref = {A or 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")

这会产生: 在此处输入图像描述 但这肯定不是你想要的。这只是为了说明您可以使用 position="identity"、position="dodge" 和各种宽度值。

创建摘要数据框

在 ggplot 中,你几乎总是可以通过处理数据框本身来得到你想要的。这是另一个使用汇总数据的尝试,它包含 y 总计,并且当 ref 为“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

产生: 在此处输入图像描述

希望这能让你更接近你的想法。

于 2013-08-20T21:26:51.253 回答