Skip to content

Conversation

DavisVaughan
Copy link
Member

@DavisVaughan DavisVaughan commented May 10, 2023

Closes #233

library(ggplot2)
library(clock)
library(vctrs)
set.seed(1234)

from <- year_month_day(2019, 1)

df <- vec_rbind(
  data_frame(
    g = "stock 1",
    date = from + duration_months(cumsum(sample(1:2, size = 100, replace = TRUE))),
    price = cumsum(1 + rnorm(100))
  ),
  data_frame(
    g = "stock 2",
    date = from + duration_months(cumsum(sample(1:2, size = 100, replace = TRUE))),
    price = cumsum(1 + rnorm(100))
  )
)

# Defaults automatically know you have monthly data
ggplot(df, aes(date, price, group = g, color = g)) +
  geom_line()

# Fully customize as needed
ggplot(df, aes(date, price, group = g, color = g)) +
  geom_line() +
  scale_x_year_month_day(
    date_breaks = duration_months(24),
    date_minor_breaks = duration_months(6),
    date_labels = "%Y"
  )

ggplot(df, aes(date, price, group = g, color = g)) +
  geom_line() +
  scale_x_year_month_day(
    date_labels = "%B\n%Y",
    date_locale = clock_locale("fr")
  )

economics$date <- as_year_month_day(economics$date)
economics$date <- calendar_narrow(economics$date, "month")

ggplot(economics, aes(x = date, y = unemploy, fill = date)) +
  geom_col()

set.seed(1234)

from1 <- year_quarter_day(2019, 1)
from2 <- year_quarter_day(2000, 2)

df <- vec_rbind(
  data_frame(
    g = "stock 1",
    date = from1 + duration_quarters(cumsum(sample(1:5, size = 50, replace = TRUE))),
    price = cumsum(1 + rnorm(50))
  ),
  data_frame(
    g = "stock 2",
    date = from2 + duration_quarters(cumsum(sample(1:5, size = 50, replace = TRUE))),
    price = cumsum(1 + rnorm(50))
  )
)

ggplot(df, aes(date, price, group = g, color = g)) +
  geom_line()

# Zooming with `coord_cartesian()`
ggplot(df, aes(date, price, group = g, color = g)) +
  geom_line() +
  coord_cartesian(xlim = year_quarter_day(c(2020, 2040), 1))

Created on 2023-05-10 with reprex v2.0.2.9000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature request: scales for ggplot2
1 participant