Search code examples
rggplot2dplyr

Add horizontal lines y-axis ggplot


I have a dataframe like data:

# Libraries
library(ggplot2)
library(dplyr)

# Generate database
set.seed(123)
data <- data.frame(
  date = seq.Date(from = as.Date("2023-01-01"), to = as.Date("2023-12-31"), by = "day"),
  value = runif(365, min = 50, max = 100)
)

# Create ggplot
ggplot(data, aes(x = date, y = value)) +
  geom_line(color = "blue") +
  theme(panel.background = element_blank())

I would like to include horizontal light gray lines for each of the values represented in the y-axis automatically. I have tried the following code without any success:

# Create ggplot
ggplot(data, aes(x = date, y = value)) +
  geom_line(color = "blue") +
  theme(panel.background = element_blank())+
  geom_hline(yintercept = value)

Any help?


Solution

  • To render a horizontal line for each of the breaks in the y scale, use

    theme(panel.background = element_blank(),
            panel.grid.major.y = element_line(color = "gray"),
      )