最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - How do you remove "padded" dates in ggplot without "cutting" the boxplot? - Stack Overfl

programmeradmin1浏览0评论

With longer date ranges ggplot adds an extra date before and after the date range. This is annoying as it seems there is no data for those dates (also not the range I selected).

The solutions offered work well with other type of charts, but for boxplots they "cut" the first and last boxplot, as shown here:

Any suggestions? Here is the code to generate these:

library(tidyverse)
# Sample data frame
dates <- seq(as.Date("2025-02-01"), by = "day", length.out = 30)
means <- rnorm(30, mean = 10, sd = 2) 
y <- unlist(lapply(means, function(mean) rnorm(20, mean = mean, sd = 1)))
df <- tibble(
  date = rep(dates, each = 20),
  y = y)

# First plot
ggplot(df, aes(x=date, y = y, group = date)) +
  geom_boxplot() +
  scale_x_date(date_labels = "%a \n%m/%d",
               date_breaks = "1 day",
               labels = scales::labels_wrap())


# Second plot
ggplot(df, aes(x=date, y = y, group = date)) +
  geom_boxplot() +
  scale_x_date(date_labels = "%a \n%m/%d",
               date_breaks = "1 day",
               labels = scales::labels_wrap(),
               expand = expansion(0),
               limits = c(min(df$date),
                          max(df$date)))

With longer date ranges ggplot adds an extra date before and after the date range. This is annoying as it seems there is no data for those dates (also not the range I selected).

The solutions offered work well with other type of charts, but for boxplots they "cut" the first and last boxplot, as shown here:

Any suggestions? Here is the code to generate these:

library(tidyverse)
# Sample data frame
dates <- seq(as.Date("2025-02-01"), by = "day", length.out = 30)
means <- rnorm(30, mean = 10, sd = 2) 
y <- unlist(lapply(means, function(mean) rnorm(20, mean = mean, sd = 1)))
df <- tibble(
  date = rep(dates, each = 20),
  y = y)

# First plot
ggplot(df, aes(x=date, y = y, group = date)) +
  geom_boxplot() +
  scale_x_date(date_labels = "%a \n%m/%d",
               date_breaks = "1 day",
               labels = scales::labels_wrap())


# Second plot
ggplot(df, aes(x=date, y = y, group = date)) +
  geom_boxplot() +
  scale_x_date(date_labels = "%a \n%m/%d",
               date_breaks = "1 day",
               labels = scales::labels_wrap(),
               expand = expansion(0),
               limits = c(min(df$date),
                          max(df$date)))
Share Improve this question asked Feb 7 at 0:58 seansteeleseansteele 7493 silver badges15 bronze badges 4
  • 5 scale_x_date(date_labels = "%a \n%m/%d", date_breaks = "1 day", labels = scales::labels_wrap(), expand = expansion(add = c(0.1,0.1))) – Jon Spring Commented Feb 7 at 1:05
  • Why does this have to be so hard?!?
发布评论

评论列表(0)

  1. 暂无评论