Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular histogram in ggplot2 with even spacing of bars and no extra lines

Tags:

r

ggplot2

I'm working on making a circular histogram in ggplot2 that shows how the number of calls varies over 24 hours. My dataset starts at 0 and goes to 23, with the number of calls per hour:

df = data.frame(xvar = 0:23, 
                y = c(468,520,459,256,397,241,117,120,45,100,231,398,340,276,151,134,157,203,308,493,537,462,448,383))

I'm using the following code to create the circular histogram:

ggplot(df, aes(xvar, y)) +
    coord_polar(theta = "x", start = -.13, direction = 1) +
    geom_bar(stat = "identity", fill = "maroon4", width = .9) +
    geom_hline(yintercept = seq(0, 500, by = 100), color = "grey80", size = 0.3) +
    scale_x_continuous(breaks = seq(0, 24), labels = seq(0, 24)) +
    xlab("Hour") +
    ylab("Number of Calls") +
    ggtitle("Number of Calls per Hour") +
    theme_bw()

I really like the resulting plot:

Circular histogram

but I can't figure out how to get the same spacing between the 23 and 0 bars as is present for the other bars. Right now, those two bars are flush against one another and nothing I've tried so far will separate them. I'm also interested in removing the lines between the different hours (ex. the line between 21 and 22) since it's somewhat distracting and doesn't convey any information. Any advice would be much appreciated, particularly on spacing the 23 and 0 bars!

like image 442
TAH Avatar asked Oct 18 '22 15:10

TAH


1 Answers

You can use the expand parameter of scale_x_continuous to adjust. Simplified a little,

ggplot(df, aes(x = xvar, y = y)) +
    coord_polar(theta = "x", start = -.13) +
    geom_bar(stat = "identity", fill = "maroon4", width = .9) +
    geom_hline(yintercept = seq(0, 500, by = 100), color = "grey80", size = 0.3) +
    scale_x_continuous(breaks = 0:24, expand = c(.002,0)) +
    labs(x = "Hour", y = "Number of Calls", title = "Number of Calls per Hour") +
    theme_bw()

plot with space between 23 and 0

like image 126
alistaire Avatar answered Oct 21 '22 04:10

alistaire