0

Does someone know why 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")
s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • 6
    Can you post sample data? Please edit **the question** with the output of `dput(sp500400_all_mkt_Y)`. Or, if it is too big with the output of `dput(head(sp500400_all_mkt_Y, 20))`. – Rui Barradas Dec 04 '18 at 14:30
  • 3
    In order to get the `linetype` to appear in the legend, you need to rewrite the `geom_line()` to a single call with the linetype mapped in the `aes()` in the first line of the code. I would guess you will need to reshape your data to long format so that all the returns are in a single column with another column indicating bottom/medium/top. – qdread Dec 04 '18 at 14:38
  • [This question](https://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot?rq=1) has the exact problem you did with not seeing a legend (though theirs is color, not linetype), and has an answer showing how to fix this. – Jan Boyer Dec 04 '18 at 15:49

0 Answers0