Robin
Robin

Reputation: 459

How to merge the legends in ggpplot

I have trouble merging the legend, the current result had assigned linetype, size, shape and colour seperately.

My data look like this:

library(ggplot2)
library(dplyr)
library(reshape2)
library(patchwork)
library(hrbrthemes)

rate="rate"
Jul="0.5‰"
Aug="0.6‰"
Sep="0.7‰"

df <- data.frame(rate,Jul,Aug,Sep)
df
d=melt(df,measure.vars = names(df)[2:4])
d
d$month=as.factor(d$variable)
d$percent=as.numeric(gsub("‰","",d$value))

And I plot the data by using ggplot2:

ggplot(d,aes(x=month,y=percent)) + 
  geom_point(aes(x=month,y=percent,color="Rate",shape="Rate"), size=2) +
  geom_text(aes(label = paste(format(percent, digits = 4, format = "f"), "‰")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = percent, group=1, color="Rate",linetype = "Rate",size="Rate")) + 
  geom_hline(aes(yintercept=1,color="Target",linetype="Target",size="Target"))+
  scale_y_continuous(breaks = seq(0,1.1,0.2), 
                     labels = paste0(seq(0,1.1,0.2)," ‰")) +
  expand_limits(y = c(0, 1.1)) +
  labs(y="", x="") + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D")) +
  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed")) +
  scale_shape_manual(values = c(Rate = 16, Target = NA)) +
  scale_size_manual(values = c(Rate = 1, Target = .7)) +
  theme(legend.key=element_blank(),legend.position="bottom") 

The result of legend looked very messy:

enter image description here

I would like the legend look like as below:

enter image description here

So how to modify the code to merge the legend?

Thanks very much!

Upvotes: 2

Views: 58

Answers (1)

Jon Spring
Jon Spring

Reputation: 66415

If we give the legends the same name, ggplot will try to merge them:

...
scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D"), name = "Legend") +
  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed"), name = "Legend") +
  scale_shape_manual(values = c(Rate = 16, Target = NA), name = "Legend") +
  scale_size_manual(values = c(Rate = 1, Target = .7), name = "Legend") +
  theme(legend.key=element_blank(),legend.position="bottom") 

enter image description here

Upvotes: 5

Related Questions