1

I have below ggplot

library(ggplot2)
library(quantmod)
dat = data.frame(x = as.yearqtr(seq(as.Date('2002-01-01'), length.out = 17, by = '95 day')),
                    y2 = c(19747, 19343, 19007, 18336, 17534, 16548, 15536, 14400, 13428, 12686, 11877, 11250, 10625, 10122, 9740, 9314, 8892))

ggplot(dat, aes(x = x)) +
  geom_col(aes(y = y2), fill = 'red') +
  scale_x_yearqtr(limits = c(dat$x[1], dat$x[17]))

While this is working fine, I am getting below warning

Warning message:
Removed 2 rows containing missing values (geom_col). 

So basically, ggplot is removing first and last observations. Is there any way to retain them forcefully while keeping the present layout?

Brian Smith
  • 1,200
  • 4
  • 16

1 Answers1

2

You can remove scale_x_yearqtr(limits = c(dat$x[1], dat$x[17])) to make it work.

If you wish to keep the scale_x function, then one of the very low-level solution is to play around with your limits argument. Just add a little bit of padding to the limits to expand it.

library(ggplot2)

ggplot(dat, aes(x = x)) +
  geom_col(aes(y = y2), fill = 'red') +
  scale_x_yearqtr(limits = c(dat$x[1] - 0.1, dat$x[17] + 0.4))

limits_padding

benson23
  • 16,369
  • 9
  • 19
  • 38
  • While this is working, I am wondering if there can be some other way without adding artificial padding at left and right sides. Is it possible to show may be partially the leftmost and rightmost bars without extending the axis? – Brian Smith Mar 26 '22 at 09:04
  • Or may be, making the leftmost bar as left aligned and rightmost bar as right aligned. All middle bars stay as-is i.e. centre aligned. Is it possible to achieve this? – Brian Smith Mar 26 '22 at 09:06
  • @BrianSmith You can replace `scale_x_yearqtr(limits = c(dat$x[1] - 0.1, dat$x[17] + 0.4))` with this line of code `coord_cartesian(xlim=c(dat$x[1], dat$x[17]))` , this set limits successfully without needing to play around with other parameters, see more [here](https://stackoverflow.com/questions/25685185/limit-ggplot2-axes-without-removing-data-outside-limits-zoom) :) – benson23 Mar 27 '22 at 14:21