Why ggplot2 legend not show in the graph

2019-02-26 21:05发布

问题:

I use ggplot to scatterplot 2 datasets and want to show the legend in the top left. I tried some code but didn't work. I am not sure why this happened.

ggplot(mf, aes(log10(mf[,2]),mf[,1])) 
+ ggtitle("Plot") 
+ geom_point(color = "blue") +  theme(plot.margin = unit(c(1,2,1,1), "cm"))
+ xlab("xxx") + ylab("yyy") 
+ theme(plot.title = element_text(size=18,hjust = 0.5, vjust=4)) 
+ geom_point(data=mf2,aes(log10(mf2[,2]),mf2[,1]),color="red") 
+ theme(axis.title.x = element_text(size = rel(1.3))) 
+ theme(axis.title.y = element_text(size = rel(1.3))) 
+ scale_color_discrete(name = "Dataset",labels = c("Dataset 1", "Dataset 2"))

回答1:

Since values were not provided, I have used my own values for the demonstration purpose.

mf is a dataframe with log and val as it's column.

You need to put the color parameter inside the aesthetics. This will result in the mapping of colors for the legend. After that you can manually scale the color to get any color you desire.

you can use the below code to get the desired result.

ggplot(mf, aes(val,log))+
    geom_point(aes(color = "Dataset1"))+
    geom_point(data=mf2,aes(color="Dataset2"))+
    labs(colour="Datasets",x="xxx",y="yyy")+
    theme(legend.position = c(0, 1),legend.justification = c(0, 1))+
    scale_color_manual(values = c("blue","red"))



回答2:

Does someone know thy no legend appears in the graph when using the code below?

sp500400_percentiles_mkt <- ggplot(sp500400_all_mkt_Y,aes(x=date)) +
  geom_line(aes(y=sp500400_mkt_rblowvolatility_returns_bottom_pf_cum_2), linetype="solid")+
  geom_line(aes(y=sp500400_mkt_rblowvolatility_returns_medium_pf_cum_2), linetype="dashed")+
  geom_line(aes(y=sp500400_mkt_rblowvolatility_returns_top_pf_cum_2), linetype="dotted")+
  theme_classic()+
  theme(legend.position="bottom")+
  labs(title="Cumulative Returns: Investment of $1 in February 1998")+
  # labs(x="Year")+
  # labs(y="Cumulative Return")+
  theme(plot.title=element_text(hjust=0, size=10))+
  theme(axis.text.x = element_text(angle = 0, vjust = 0.5),axis.text=element_text(size=8))+
  scale_y_continuous(name=NULL, breaks=seq(0.00,3.00,0.2), 
                     expand=c(0,0), limits=c(0,3.00))+
  scale_x_date(name=NULL, date_breaks="1 years", date_labels="%b
  %y")

Best regards,
Patrick


标签: r ggplot2 legend