Sss
Sss

Reputation: 447

Add vertical lines connecting point to a horizontal line in a plot in R

I am plotting some values of autocorrelation in a R:

  plot(y=lag[2:N],x=1:(N-1), xlab="lag",ylab="Autocorrelation",ylim=c(-1,1), pch=16,col="red")
  abline(h=0, col="black")
  abline(h=up, col="blue")
  abline(h=low, col="blue")

This is my code and this is what I got in R enter image description here

However, I want something like the image below, where I connect the points with a red line to the horizontal line at 0.

enter image description here

Any idea how to do it?

Upvotes: 1

Views: 1543

Answers (2)

Wolfgang Arnold
Wolfgang Arnold

Reputation: 1252

If using ggplot this should do:

plot_df = data.frame(x = 1:20, y = rnorm(20))

ggplot(plot_df, aes(x, y, ymax = y, ymin = 0)) +
    geom_pointrange(color = "red") +
    geom_hline(yintercept = min(plot_df$y), color = "blue") +
    geom_hline(yintercept = max(plot_df$y), color = "blue")

Upvotes: 1

Tech Commodities
Tech Commodities

Reputation: 1959

You can add vertical lines with type = "h", and then add the points separately

plot(y=lag[2:N],x=1:(N-1), xlab="lag",ylab="Autocorrelation",ylim=c(-1,1), col="black", type = "h") 
points(y=lag[2:N],x=1:(N-1), xlab="lag", ylim=c(-1,1), pch=16,col="red", type = "p")

Upvotes: 1

Related Questions