Question

I have the following data frame

head(d[, c(1,2,7)], 10)
         date hour total_sess
2  2014-04-06   00        115
3  2014-04-07   01          3
4  2014-04-07   16          3
5  2014-04-07   21        115
6  2014-04-08   00        115
7  2014-04-08   06          3
8  2014-04-09   05          3
9  2014-04-09   11        201
10 2014-04-09   14          3
11 2014-04-09   20          3

How do i use ggplot to plot a bar chart with X-Axis = hour (indicating date along the Axis) and Y Axis as total_sess

I tried the following but was unable to generate a continuous flow

ggplot(data = d, aes(x = hour, y = total_sess, fill = factor(date)) +
 geom_bar(stat='identity') +
 theme(axis.text.x = element_text(angle = 90, hjust = 0.5))
Was it helpful?

Solution

I would convert columns 'date' and 'hour' to as.POSIXct to use as x axis. In the data you show, 'hour' seems to be a character variable (leading zeroes), and you can create a time variable like this:

d$time <- as.POSIXct(paste0(d$date, " ", d$hour, ":00:00"))

The 'time' variable can be used as x variable, and colour by date isn't really necessary (but can of course be added if you wish).

ggplot(data = d, aes(x = time, y = total_sess)) +
  geom_bar(stat='identity') +
  theme_bw()

enter image description here

When your x variable is of class as.POSIXct, you may use scale_x_datetime. Then it's easy to format the x axis with the breaks = date_breaks and labels = date_format arguments (load library(scales). See examples here

OTHER TIPS

What about using geom_tile:

library(lubridate)
library(ggplot2)
ggplot(data = data, aes(x = hour, y = ymd(date))) +
  geom_tile(aes(fill=total_sess)) +
  theme_bw()

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top