My data looks like this:

month=c("Jan","Feb","Mar","Apr","May","Jun")rate=c(70,80,90,85,88,76) dd=data.frame(month,rate)dd$type="Rate"dd$month=factor(dd$month)

I tried to create the plot like this:

ggplot(dd,aes(x=month,y=rate,color=type)) + geom_point(aes(x=month,y=rate, group=1), size=2) +geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), color="black",vjust = -0.5, size = 3.5) +geom_line(aes(x = month, y = rate, group=1), size=1) + geom_hline(aes(yintercept=85), linetype='dashed',colour="#F8766D", show.legend=T) +labs(y="", x="") + scale_colour_manual(values = c("#00BFC4")) +scale_fill_discrete(limits = c("Target")) +theme(legend.position="bottom") +theme(legend.title = element_blank()) 

enter image description here

As you can see, the legend of Rate and Target are overlapping together (there is red dash line in the green line), I'd like to know how to create the legend for Target and Rate in the correct way. Thanks!

1

Best Answer


One option to achieve your desired result would be to map on aesthetics and make use of scale_xxx_manual instead of setting the color, linetypes, ... via arguments:

month=c("Jan","Feb","Mar","Apr","May","Jun")rate=c(70,80,90,85,88,76) dd=data.frame(month,rate)dd$type="Rate"dd$month=factor(dd$month)library(ggplot2)ggplot(dd,aes(x=month,y=rate, color="Rate", linetype = "Rate")) + geom_point(aes(x=month,y=rate, shape = "Rate"), size=2) +geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), color="black",vjust = -0.5, size = 3.5) +geom_line(aes(x = month, y = rate, group=1, size = "Rate")) + geom_hline(aes(yintercept=85, color = "Target", linetype = "Target", size = "Target")) +labs(y = NULL, x= NULL, color = NULL, linetype = NULL, shape = NULL, size = NULL) + 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 = .5)) +theme(legend.position="bottom")