Boris Preger
Boris Preger

Reputation: 23

Creating a legend in ggplot2 for rectangle colors

So I'm trying something a little unique with ggplot2. I'm scoring users based on their score in a standard deviation of a distribution and then putting a differently colored rectangle over their score depending on their range. In this case, anything 1+ SD from the mean is high, -1 or lower SD from the mean is low and anything else is medium.

What I'm trying to do is to create a legend for the rectangles where it says what range each color is.

Here's a sample data frame and code

df <- data.frame(scale = factor(c("Self-Awareness","Enthusiasm","Composure","Assuredness","Sincerity")), 
                 scores = c(0.18,-3.0,0.1,1.3,0.67))

base<- ggplot(data=df, aes(x=scale, y=scores,ymin=-3.0,ymax=3.0,group=1))  + 
         stat_identity(geom="tile",width=0.8,fill=scale) + 
         geom_hline(aes(yintercept=-3.0),color="white", alpha=0.1) + 
         geom_hline(aes(yintercept=3.0),color="white", alpha=0.1)

I did a bit of a hack on the second part where I inserted lines at the top and bottom so the graph would scale properly rather than zoom in. If there's a better way, please let me know

base2<- base + 
         geom_rect(xmin=0.6, xmax= 1.4, ymin=1, ymax= 3, alpha=0.1,fill="#D53AFF") + 
         geom_rect(xmin=1.6, xmax= 2.4, ymin=-1, ymax= 1, alpha=0.1,fill="#278FF7") + 
         geom_rect(xmin=2.6, xmax= 3.4, ymin=-3, ymax= -1, alpha=0.1,fill="#2DF5F9") + 
         geom_rect(xmin=4.6, xmax= 5.4, ymin=-1, ymax= 1, alpha=0.1,fill="#278FF7") + 
         geom_rect(xmin=3.6, xmax= 4.4, ymin=-1, ymax= 1, alpha=0.1,fill="#278FF7")

So I would like a legend that says that the range of #D53AFF is "High", the range of #278FF7 is "Medium" and the range of #278FF7 is "Low". Any help with this is greatly appreciated.

Upvotes: 2

Views: 1275

Answers (1)

joran
joran

Reputation: 173577

Everything in ggplot2 revolves around placing your data in a single data frame and mapping variables to aesthetics:

rect_df <- data.frame(xmin = c(0.6,1.6,2.6,4.6,3.6),
                      xmax = c(1.4,2.4,3.4,5.4,4.4),
                      ymin = c(1,-1,-3,-1,-1),
                      ymax = c(3,1,-1,1,1),
                      grp = factor(c('High','Medium','Low','Medium','Medium'),
                                   levels = c(c('Low','Medium','High'))))

base + 
    geom_rect(data = rect_df,aes(x = NULL,y = NULL,xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax,fill = grp),
                alpha = 0.5) + 
    scale_fill_manual(values = c('#2DF5F9','#278FF7','#D53Aff'))

Upvotes: 3

Related Questions