简体   繁体   中英

How to make a custom legend when a plot overlays another using ggplot?

I need to make a stacked histogram plotting two different variables. There is a variable called T1 , and another variable called T2 . These two variables have two different states, one that happened before, and another that happened after. I want to have one plot where I'll show both T1 and T2 in one column, their state before and after, but using two different colours (one that indicates the state before, and another that indicates the state after).

This is the code snippet I have so far:

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"))

So the plot looks amazing, however my question is now, how can I get a proper legend? So I need to have one colour for "After" and another for "Before" , but not as lines, rather as filled boxes.

First, as you are making barplot then use geom_bar() . Then for the fill= and color= inside aes() use the same names and then adjust color and fill with scale_.. functions.

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"))

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM