Ana Raquel Ana Raquel -4 years ago 148
R Question

How to increase x-axis tickmark frequency using ggplot

I have this plot but i want to add more x values.

I've already tried "scale_x_continuous" but this doesn't work because my values are not numbers, but dates.

how can i solve this?

Thank you!

enter image description here

Answer Source

If by "more x values" you mean that you would like to have more labels on your x-axis, then you can adjust the frequency using the scale_x_dates argument like so:

scale_x_date(date_breaks = "1 month", date_labels = "%b-%y")

Here is my working example. Please post your own if I misunderstood your question:

library("ggplot2")
# make the results reproducible
set.seed(5117)  

start_date <- as.Date("2015-01-01") 
end_date <- as.Date("2017-06-10")

# the by=7 makes it one observation per week (adjust as needed)
dates <- seq(from = start_date, to = end_date, by = 7)
val1 <- rnorm(length(dates), mean = 12.5, sd = 3)

qnt <- quantile(val1, c(.05, .25, .75, .95))

mock <- data.frame(myDate = dates, val1)

ggplot(data = mock, mapping = aes(x = myDate, y = val1)) +
  geom_line() +
  geom_point() +
  geom_hline(yintercept = qnt[1], colour = "red") +
  geom_hline(yintercept = qnt[4], colour = "red") +
  geom_hline(yintercept = qnt[2], colour = "lightgreen") +
  geom_hline(yintercept = qnt[3], colour = "lightgreen") +
  theme_classic() +
  scale_x_date(date_breaks = "1 month", date_labels = "%b-%y") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download