Search code examples
rmatlabstem

How to create stem plot in R?


enter image description hereI want to create a stem plot in R. I do have a matlab code but do not know how to write the same code in R. The matlab code as follow

x = 0:25;
y = [exp(-.07*x).*cos(x);exp(.05*x).*cos(x)]';
h = stem(x,y);
set(h(1),'MarkerFaceColor','blue')
set(h(2),'MarkerFaceColor','red','Marker','square')

h(1) is the handle to the stemseries object plotting the expression exp(-.07*x).*cos(x).
h(2) is the handle to the stemseries object plotting the expression exp(.05*x).*cos(x).

Solution

  • Here is a starting point for your code.

    x <- 0:25
    y <- cbind(exp(-.07*x)*cos(x), exp(.05*x)*cos(x))
    
    df <-  data.frame(y=c(exp(.05*x)*cos(x),exp(-.07*x)*cos(x)),
       x=rep(x,2), grp=factor(rep(c(1,2),each=length(x))))
    
    library(ggplot2)
    p <- ggplot(aes(group=grp, col=grp, shape=grp), data=df) + 
        geom_hline(aes(yintercept=0)) +
        geom_segment(aes(x,y,xend=x,yend=y-y)) + 
        geom_point(aes(x,y),size=3) 
    p
    

    enter image description here