axis values are -6,-4,-2, 0, 2,4, 6 with some y values in a density plot. Is it possible to Add dotted vertical lines on certain x-axis values (Forex: -3 and +3 )using ggplot ?
library(ggplot2) df <- data.frame(x = rnorm(1000, 0, 1), y = rnorm(1000, 0, 2), z = rnorm(1000, 2, 1.5)) df.m <- melt(df) ggplot(df.m) + geom_freqpoly(aes(x = value, y = ..density.., colour = variable))
To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a wide vertical line with different color then lwd and colour argument will be used. The lwd argument will increase the width of the line and obviously colour argument will change the color.
How to take horizontal line red dashed? Replace your geom_hline() with geom_hline(yintercept = 40, linetype = 2, colour = "red") and it should be dashed and red.
The R function abline() can be used to add vertical, horizontal or regression lines to a graph. A simplified format of the abline() function is : abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)
Example: To add the horizontal line on the plot, we simply add geom_hline() function to ggplot2() function and pass the yintercept, which basically has a location on the Y axis, where we actually want to create a vertical line. Here we set 20 to the xintercept.
Try geom_vline
:
ggplot(df.m) + geom_freqpoly(aes(x=value, y=..density.., colour=variable)) + geom_vline(xintercept=c(-3,3), linetype="dotted")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With