如何更改以下条形图以便:
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
答案 0 :(得分: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")
这会产生: 但这肯定是不你想要的。这只是为了说明你可以使用position =“identity”,position =“dodge”和各种宽度值。
在ggplot中,您几乎总能通过处理数据框本身获得所需的内容。这是另一种尝试,其中汇总数据保存了y-totals,并且当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
产生:
希望这能让你更接近你的想法。