Reputation: 1988
In base R, I like to make plots with time on the x-axis where the labels are shown in between long tick marks. For example, there may be tick marks at June 1 and June 31, but the text "June" shows up in between, centered around June 15. In base R, I simply draw 2 axes, one with the ticks and one with the labels.
However, I haven't been able to figure out how to make this style of axis in ggplot2.
labels = c("","June","")
almost works but tick marks only accept one length so something like axis.ticks.length = unit(c(.25,0,.25),"cm")
doesn't work.I think something like this might be possible with the ggh4x
package but I haven't been able to figure it out. I will be happy for any solution compatible with ggplot2, regardless of which package.
Upvotes: 0
Views: 626
Reputation: 2321
Have you looked into the scales
package? Instead of manually creating x-axis ticks and labels, you can specify exactly how many x-axis tick marks and labels you want with breaks_pretty
and specify date formatting with label_date
. More info on date formatting here.
library(tidyverse)
library(scales)
time <- seq(as.Date("2020-1-1"), as.Date("2022-1-1"), by = "months")
var <- c(1:15, 15:6)
df <- data.frame(var, time) %>%
mutate(time = as.Date(time))
# original
df %>%
ggplot(aes(x = time, y = var)) +
geom_bar(stat = "identity")
# just month names
df %>%
ggplot(aes(x = time, y = var)) +
geom_bar(stat = "identity") +
scale_x_date(labels = label_date("%B"))
# increase tick marks with month names and full year
df %>%
ggplot(aes(x = time, y = var)) +
geom_bar(stat = "identity") +
scale_x_date(labels = label_date("%B %Y"),
breaks = breaks_pretty(n = 12)) # <- change 12 to another number
Upvotes: 0