我需要制作一个堆积直方图,绘制两个不同的变量。有一个名为T1
的变量,另一个名为T2
的变量。这两个变量有两种不同的状态,一种发生在之前,另一种发生在之后。
我希望有一个情节,我将在一列中显示T1
和T2
,它们的状态在前后,但使用两种不同的颜色(一种指示之前的状态,另一种指示之后的州。
这是我到目前为止的代码段:
pre <- as.data.frame( matrix( nrow=2,ncol=2,byrow=TRUE,c(60,"T1",40,"T2") ) )
post <- as.data.frame( matrix( nrow=2,ncol=2,byrow=TRUE,c(70,"T1",50,"T2") ) )
pre$V1 <- as.numeric(as.character(pre$V1))
post$V1 <- as.numeric(as.character(post$V1))
ggplot() +
geom_histogram(stat="identity", fill=c(rep("red",2)), data=post, aes(x=V2, y=V1, fill=V2, colour="Before")) +
geom_histogram(stat="identity", fill=c(rep("green",2)), data=pre, aes(x=V2, y=V1, fill=V2, colour="After")) +
scale_x_discrete("x axis") +
scale_y_continuous("y axis", limits = c(0, 100)) +
scale_colour_manual(values = c("red","green"))
所以情节看起来很神奇,但是现在我的问题是,我怎样才能得到一个合适的传奇?所以我需要为"After"
设置一种颜色,为"Before"
设置另一种颜色,但不要为行,而不是填充框。
答案 0 :(得分:6)
首先,在制作条形图时,请使用geom_bar()
。然后,对于fill=
内的color=
和aes()
使用相同的名称,然后调整颜色并填充scale_..
个函数。
ggplot() +
geom_bar(stat="identity", data=post, aes(x=V2, y=V1, fill="Before",color="Before")) +
geom_bar(stat="identity", data=pre, aes(x=V2, y=V1, fill="After",color="After")) +
scale_x_discrete("x axis") +
scale_y_continuous("y axis", limits = c(0, 100)) +
scale_fill_manual("Legend",values = c("green","red"))+
scale_color_manual("Legend", values = c("red","green"))