Home > OS >  Why Two Legends are generated by ggplot
Why Two Legends are generated by ggplot

Time:09-17

I am new to R, where I need to generate multiple lines graph (with dual axes). I have no idea why R generates 2 legends to me with the code below. Can anyone please advise me on how to merge the two legends, thanks?

library(ggplot2)


loc=rep(1:3, times=6) #x-axis value

Cate=rep(c("Ali", "Ben", "Can", "Don", "Ele", "Fin"), each=3) #category

res=rnorm(18,5,1) #y-axis value

df1=data.frame(loc, res, Cate)

df1$Cate=factor(df1$Cate, levels=c("Ali","Ben","Can","Don","Ele","Fin"))

f=ggplot(data=df1, aes(x=loc, y=res, group=Cate, colour=Cate))  
  geom_line(aes(linetype=Cate), size=1)  
  labs(title="My Title", x="X-Axis", y="Y-Axis")   
  scale_y_continuous(n.breaks=8, sec.axis=sec_axis(~exp(.), name="Exp Y-Axis"))  
  scale_colour_discrete(labels=c(expression(paste(italic("Ali"))), expression(paste(italic("Ben"))),
                      expression(paste(italic("Can"))), expression(paste(italic("Don"))),
                      expression(paste(italic("Ele"))), expression(paste(italic("Fin")))))  
  theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank(), 
        panel.background=element_blank(), axis.line=element_line(color = "black"),
        legend.background=element_blank(), legend.key=element_rect(fill=NA))

f

CodePudding user response:

Instead of scale_colour_manual, use theme

ggplot(data=df1, aes(x=loc, y=res, group = Cate, colour=Cate))  
  geom_line(aes(linetype=Cate), size=1)  
  labs(title="My Title", x="X-Axis", y="Y-Axis")   
  scale_y_continuous(n.breaks=8, sec.axis=sec_axis(~exp(.), name="Exp Y-Axis"))  
  theme(legend.text = element_text(face = "italic")) 
  theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank(), 
        panel.background=element_blank(), axis.line=element_line(color = "black"),
        legend.background=element_blank(), legend.key=element_rect(fill=NA))

theme

  • Related