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")
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")
Perfect! Vlw!!!
– Fillipe