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
,dnorm
andcos
.Sinceitissupereasytousecolorpalettesinggplot2
,itisbettertosetthecolorsinthisway,asthecaptionbecomesmoreintuitiveanditistrivialtochangecolorsthroughthescale_color_brewer
command.
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")