我需要制作一个堆积直方图,绘制两个不同的变量.有一个名为变量的变量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"))
Run Code Online (Sandbox Code Playgroud)
因此情节看起来很神奇,但是现在我的问题是,我怎样才能得到一个合适的传奇?所以我需要有一种颜色"After"和另一种颜色"Before",但不是作为线条,而是填充框.
首先,当你正在制作barplot然后使用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"))
Run Code Online (Sandbox Code Playgroud)