0

I want to demonstrate different methods in spline function by ggplot. For example,

x=c(0,2,5)
y=c(1,4,29)
xout=seq(0,6,0.5)

First, I calculate different interpolations:

s1=spline(x,y,xout=xout,method='natural')
s2=spline(x,y,xout=xout,method='fmm')
s3=spline(x,y,xout=xout,method='hyman')

Then, plot each interpolation

library(ggplot2)
ggplot(as.data.frame(s1),aes(x,y)) +
  geom_line(size=1.2,col='red') +
  geom_line(data=as.data.frame(s2),size=1.2,col='blue') +
  geom_line(data=as.data.frame(s3),size=1.2,col='green') +
  geom_point(data=data.frame(x=x,y=y),size=4)

https://i.imgur.com/9jQEGr4.png

But, I cannot get the legend for each method and scale_color_brewer does not work, too.

What are the correct steps to get this job done?

Kattern
  • 2,679
  • 4
  • 17
  • 26

1 Answers1

0

I guess the intent of the question is (1) to colour individual spline at will and (2) to show corresponding legend. Thus I just modify your code slightly to make it work.

cols <- c('natural'='red','fmm'='blue','hyman'='green') # <- you could modify the colour here
ggplot(as.data.frame(s1),aes(x,y)) +
  geom_line(size=1.2, aes(colour='natural')) + # you need aes() to ensure it shows in the legend
  geom_line(data=as.data.frame(s2),size=1.2, aes(colour='fmm')) +
  geom_line(data=as.data.frame(s3),size=1.2, aes(colour='hyman')) +
  geom_point(data=data.frame(x=x,y=y),size=4) +
  scale_colour_manual(name='spline', values=cols, 
                      guide = guide_legend(override.aes=aes(fill=NA)))

enter image description here

KFB
  • 3,421
  • 3
  • 13
  • 18