Linetype and Shape in ggplot2 on R

Asked

Viewed 243 times

2

I am 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")

inserir a descrição da imagem aqui

I would like the shape of the lines that draw the 3 functions above to be like this:

inserir a descrição da imagem aqui

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

1 answer

2


First I will create an array with the values of x where I want the dots to be plotted. In this case, I want all dots between 0 and 2 with spacing of 0.25:

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

With this vector I will 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 have assigned parameters to 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")

inserir a descrição da imagem aqui

Note also that I did not define the colors of the lines and the dots as red, blue and green. I preferred to call them exp, dnorm and cos. How easy it is to use color palettes in ggplot2, it is better to define the colors this way, because the legend becomes more intuitive and it is trivial to change the colors through the command scale_color_brewer.

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")

inserir a descrição da imagem aqui

  • Perfect! Vlw!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.