2


I am trying to plot curves with ggplot2 and group them by maturities. In my dataset maturities are expressed in remaining time in years.
My problem is that in my whole dataset I only have two maturities (0.15 and 0.2) but the legend displays color for 0.15, 0.16, 0.17...
Here is a screenshot :

enter image description here Here is my code :

    call_vol_plot = ggplot(data=df[df$type=="C",],
       aes(x=strike,
           y=impliedVol,
           group = time_to_expiry,
           colour = time_to_expiry)) + geom_line() + geom_point(size=4, shape=21, fill="white")

    call_vol_plot = call_vol_plot + labs(title="Call Implied Volatility",
                           subtitle="Options on future contracts",
                           y="Implied Volatility",
                           x="Strike") + guides(color=guide_legend("Maturity in year"))

I tried scale_color_discrete but it didn't work. Thank you !

AlexM
  • 231
  • 2
  • 13

2 Answers2

2

Within aes, convert the time_to_expiry to factor as.factor(time_to_expiry)

and

+ scale_color_manual(values = c(0.15, 0.2))
Highland
  • 148
  • 1
  • 7
  • It worked fine but there is neither any color nor any line now – AlexM Nov 16 '17 at 22:14
  • @AlexM From the tidyverse page: http://ggplot2.tidyverse.org/reference/scale_manual.html looks maybe you can do something like `values = c(0.15 = 'red', 0.2 = 'blue'` – Highland Nov 17 '17 at 14:03
  • @Highland The problem with that solution is that you fix the possible maturities. If some additional maturities appears in the dataset, the solution won't work anymore. The solution I put in comment worked fine and for all dataset! Thanks a lot! – AlexM Nov 17 '17 at 20:17
1

Solution : Replacing time_to_expiry by as.character(time_to_expiry) work as expected. R can't make continuous values with variables of type characters.
Many thanks to @Highland that almost gave the solution!

AlexM
  • 231
  • 2
  • 13