LineType and shape in ggplot2 in R

1

I'm using the following code to plot 3 functions:

ggplot(data.frame(x = c(0, 2)), aes(x)) +
    stat_function(fun = exp, geom = "line")+
    stat_function(fun = dnorm ,geom = "line")+
    stat_function(fun = cos, colour = "blue")

Iwouldliketheshapeofthelinesthatdrawtheabove3functionstolooklikethis:

That is, the first function was punctuated with triangle, the second with asterisks and the third with points. The shapes (triangle, asterisks and points) can be any one (square, circle ...). How do I add a caption with the respective shapes for each line?

    
asked by anonymous 26.08.2017 / 15:46

1 answer

1

First, I'm going to create a vector with the values of x in which I want points to be plotted. In case, I want all points between 0 and 2, with spacing of 0.25:

x <- seq(0, 2, by=0.25)

With this vector I'm going to create a data frame with x and the values of the functions that interest me:

dados <- data.frame(x,
                    exp=exp(x),
                    dnorm=dnorm(x),
                    cos=cos(x))

Finally, I plot everything using a geom_point for each set of function points and a stat_function for each function. Note that each geom_point has a shape assigned to it. In addition, I assign parameters of colour equal to geom_point and stat_function .

ggplot(dados, aes(x=x, y=exp)) +
  geom_point(aes(colour="exp"), shape=1) +
  stat_function(fun = exp, geom = "line", aes(colour="exp")) +
  geom_point(aes(x=x, y=dnorm, colour="dnorm"), shape=2) +
  stat_function(fun = dnorm, geom = "line", aes(colour="dnorm")) +
  geom_point(aes(x=x, y=cos, colour="cos"), shape=4) +
  stat_function(fun = cos, geom = "line", aes(colour="cos")) + 
  labs(x="Eixo X", y="f(x)", colour="Legenda")

NoticealsothatIdidnotdefinethecolorsofthelinesandthepointsasred,blueandgreen.Ipreferredtocallthemexp,dnormandcos.Sinceitissupereasytousecolorpalettesinggplot2,itisbettertosetthecolorsinthisway,asthecaptionbecomesmoreintuitiveanditistrivialtochangecolorsthroughthescale_color_brewercommand.

ggplot(dados,aes(x=x,y=exp))+geom_point(aes(colour="exp"), shape=1) +
  stat_function(fun = exp, geom = "line", aes(colour="exp")) +
  geom_point(aes(x=x, y=dnorm, colour="dnorm"), shape=2) +
  stat_function(fun = dnorm, geom = "line", aes(colour="dnorm")) +
  geom_point(aes(x=x, y=cos, colour="cos"), shape=4) +
  stat_function(fun = cos, geom = "line", aes(colour="cos")) + 
  labs(x="Eixo X", y="f(x)", colour="Legenda") +
  scale_color_brewer(palette="Dark2")

    
26.08.2017 / 17:33