kl-higgins
kl-higgins

Reputation: 323

Center bin of polar plot at midpoint without losing bin in ggplot2

I am attempting to create a plot based on frequency at each cardinal direction. I followed the instructions from this excellent resource but I am running into a major issue when attempting to centre the bin in the middle (e.g. observations from NNW to N to NNE within the "North" bin). In the original example, no values were found at the extremes so it did not show up as an issue.

enter image description here

enter image description here

library(gcookbook)  # Load gcookbook for the wind data set
wind
w287<-c(0, 3.5, 9, 10, 90, 5, 358)
w288<-c(0, 3.5, 9, 10, 90, 5, 357)
w289<-c(0, 3.5, 9, 10, 90, 5, 1)
w290<-c(0, 3.5, 9, 10, 90, 5, 2)

wind2<-rbind(wind, w287, w288, w289, w290,w287, w288, w289, w290,w287, w288, w289, w290,w287, w288, w289, w290,w287, w288, w289, w290,w287, w288, w289, w290)
wind2[is.na(wind2$SpeedCat),]$SpeedCat<-">20"

#initial plot without rotation 
a<-ggplot(wind2, aes(x = DirCat)) +
  geom_histogram(binwidth = 90, boundary = 0) +
  coord_polar() +
  labs(title="Bins visible : no rotation")+
  scale_x_continuous(limits = c(0,360))

#plot with rotation in which the values from bin#1 are lost
b<-ggplot(wind2, aes(x = DirCat)) +
  geom_histogram(binwidth = 90, boundary = -45) +
  coord_polar() +
  labs(title="Bin not visible: rotation")+
  scale_x_continuous(limits = c(0,360))

c<-ggplot(wind2, aes(x = DirCat)) +
  geom_histogram(binwidth = 90, boundary = -45) +
  coord_polar() +
  labs(title="Bin visible: rotation + scale increased")+
  scale_x_continuous(limits = c(-45,405))

grid.arrange(a, b, c, ncol=3)

Upvotes: 0

Views: 62

Answers (1)

I_O
I_O

Reputation: 6921

The center argument to geom_histogram might do the trick:

## example data:
d <- data.frame(DirCat = sample(0:360, 3600, replace = TRUE))

th <-  22.5 ## wedge angle

    d |> 
      ggplot() +
      geom_histogram(aes(x = DirCat),
                     colour = 'white',
                     binwidth = th,
                     center = th/2
      ) +
      scale_x_continuous(breaks = 1:16 * th) +
      coord_polar()

arbitrarily center histogram bar

Upvotes: 1

Related Questions