0

I have the dataset :

vec=c("1960-01-01 06:39:00","1960-01-01 05:10:00","1960-01-01 04:30:00","1960-01-01 02:53:00")
vec=as.POSIXct(vec, origin="1960-01-01", tz = "GMT")
dum=data.frame(v1=c("a","b","c","d"),v2=vec)

If I try to built a plot with a line, it works :

ggplot(dum, aes(y=v2, x=v1, group=1)) + 
geom_line(colour="#59AA46")

enter image description here

But what I need is to built a barplot, so I use the following code which does not work so well :

ggplot(dum, aes(y=v2, x=v1)) + 
geom_col(fill="#59AA46")

enter image description here

What am I doing wrong ?

tjebo
  • 21,977
  • 7
  • 58
  • 94
Doe
  • 27
  • 4

1 Answers1

3

The thing is ggplot will use unix time for the axis (which is by default the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT)).

In your data the date goes back to the year 1960 which means values on the y-axis are not only negative, but they are also all below 13e+6 (number of seconds in a year).

Since geom_line or geom_point will only take these values into consideration, this fact will not cause any issue when plotting, however geom_col or geom_bar will code for each bar the start and end value and in your case it will always start at point 0 (i.e. 1970-01-01 00:00:00) and end at some point sligtly lower than 31e+6 (i.e. 1960-01-01 H:M:S).

One workaround you can do is to use unix time and the play around with the layout until you get the output you want

Here is what I mean:

# define the y-axis limits 
start_lim <- as.integer(as.POSIXct("1960-01-01 00:00:00", tz = "GMT"))
end_lim <- as.integer(as.POSIXct("1960-01-02 00:00:00", tz = "GMT"))

# plot
ggplot(dum, aes(x=v1, y=as.integer(v2))) +              # use v2 as integer
  geom_col(fill="#59AA46") +                      
  coord_cartesian(ylim = c(start_lim, end_lim)) +       # set the y limits
  scale_y_reverse(breaks = as.integer(vec),             # reverse the y axis 
                  labels = vec) +                       # set the labels and ticks as wanted
  ylab('Date-time')                                     # set the axis title

I eventually got this :

enter image description here

DS_UNI
  • 2,600
  • 2
  • 11
  • 22
  • 1
    Thank you for your answer ! Thanks to your explanation, I simply chose to change my dataset so that my data have a different date (origin="1970-01-01"). – Doe Jan 02 '19 at 15:51