Setting date limits inside geom_boxplot in ggplot2

Viewed 123

I have one question about how geom_boxplot works. First I am using date type data and try not to plot all my data, only a part.

First I load my packages

library(dplyr)
library(ggplot2)
library(tibble)
library(quantmod)

I am using getSymbols to get my data

yahoo <- getSymbols(auto.assign = F,Symbols = "QQQ")
chartSeries(yahoo,subset = "last 3 month")

I shape my data to use it in ggplot

df <- yahoo %>%
  as.data.frame() %>% 
  rownames_to_column() %>% 
  rename("time" = "rowname") %>% 
  mutate(time = as.Date(time))

I set my date limits

l <- c(df$time[10],df$time[100])

Then I try to plot it

ggplot(data = df) +
  geom_boxplot(aes(x = time,
                   lower  = QQQ.Close,
                   upper  = QQQ.Open,
                   ymin   = QQQ.Low,
                   ymax   = QQQ.High,
                   middle = QQQ.Open),
               stat = "identity") +
  scale_x_date(limits = l)

and I get error:

Error in if (df$xmin[i] >= df$xmax[i - 1]) { : 
  valor ausente donde TRUE/FALSE es necesario

I try a different way:

ggplot(data = df) +
  geom_boxplot(aes(x = time,
                   lower  = QQQ.Close,
                   upper  = QQQ.Open,
                   ymin   = QQQ.Low,
                   ymax   = QQQ.High,
                   middle = QQQ.Open),
               stat = "identity") +
  coord_cartesian(xlim = l)

The second way works but my question is: why the first plot give me error? If I try with different geom i can use the scale_x_date limits parameter. for example:

ggplot(data = df) +
  geom_line(aes(x = time,
                y = QQQ.Adjusted)) +
  scale_x_date(limits = l)

Why this doesn't work with the first plot?

0 Answers
Related