I have plotted a line plot. I have added a horizontal line on the plot. How to take horizontal line red dashed?
# Sample Data
library(tidyverse)
Month= c("Jan","Feb","Mar","Apr","May","Jun")
a = c(11,10,9,8,4,8)
test= data_frame(Month,a)
test$cum_total <- cumsum(test$a)
test$Month <- factor(test$Month, month.abb)
# ggplot
ggplot(data=test, aes(x=Month, y=cum_total, group=1)) +
geom_line()+
geom_point()+
geom_hline(yintercept=40)+
annotate("text", x = "Feb", y = 40, label = "Previous Level", vjust = -0.5)
First of all, create a data frame. Then, create a plot using ggplot2. After that, create the same plot with geom_hline function having horizontal line defined with y intercept and its type defined with line type argument.
Line types in R The different line types available in R software are : “blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, “twodash”. Note that, line types can be also specified using numbers : 0, 1, 2, 3, 4, 5, 6. 0 is for “blank”, 1 is for “solid”, 2 is for “dashed”, ….
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.
to make the horizontal line dashed and red the following arguments should be included in the geom_hline function call:
linetype = 'dotted', col = 'red'
# Sample Data
library(tidyverse)
Month= c("Jan","Feb","Mar","Apr","May","Jun")
a = c(11,10,9,8,4,8)
test= data_frame(Month,a)
test$cum_total <- cumsum(test$a)
test$Month <- factor(test$Month, month.abb)
# ggplot
ggplot(data=test, aes(x=Month, y=cum_total, group=1)) +
geom_line()+
geom_point()+
geom_hline(yintercept=40, linetype='dotted', col = 'red')+
annotate("text", x = "Feb", y = 40, label = "Previous Level", vjust = -0.5)
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