Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add dashed horizontal line with label in ggplot

Tags:

r

ggplot2

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)
like image 282
Anandapadmanathan Avatar asked Jul 24 '19 07:07

Anandapadmanathan


People also ask

How do I add a horizontal dashed line in ggplot2?

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.

What is Linetype in Ggplot?

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”, ….

How do I add a vertical line in ggplot2?

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.


1 Answers

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)

enter image description here

like image 176
Kresten Avatar answered Oct 15 '22 14:10

Kresten