Reputation: 1653
I am trying to create a circular plot to the display frequency/counts of months in my dataset but I would also like to group the months by season. Here is a similar plot for time of day, and now I would like to use the same approach to plot months/seasons. However, for some reason I can't seem to specify the right option to break my scale into non-overlapping month categories. Any suggestions are much appreciated.
library(lubridate)
library(ggplot2) # use at least 0.9.3 for theme_minimal()
library(circular)
### PLOT FOR HOURS ###
## generate random data in POSIX date-time format
set.seed(44)
N=500
events <- as.POSIXct("2011-01-01", tz="GMT") +
days(floor(365*runif(N))) +
hours(floor(24*rnorm(N))) + # using rnorm here
minutes(floor(60*runif(N))) +
seconds(floor(60*runif(N)))
# extract hour with lubridate function
hour_of_event <- hour(events)
# make a dataframe
eventdata <- data.frame(datetime = events, eventhour = hour_of_event)
# determine if event is in business hours
eventdata$Workday <- eventdata$eventhour %in% seq(6, 18)
ra<-length(eventdata[,2])
for (i in 1:ra){
if(eventdata[,3][i]=="TRUE"){eventdata$diel[i]<-"day"}else{eventdata$diel[i]<-"night"}
}
# Plot
ggplot(eventdata, aes(x = eventhour, fill = diel)) +
geom_histogram(breaks = seq(0,24), width = 2, colour = "grey") +
coord_polar(start = 0) + theme_minimal() +
scale_fill_brewer() + ylab("Count") + ggtitle("Events by Time of day") +
scale_x_continuous("", limits = c(0, 24), breaks = seq(0, 24), labels = seq(0,24))
This is my attempt to do a plot by month/season,
### PLOT FOR MONTHS ###
head(events)
# extract hour with lubridate function
month_of_event <- month(events)
# make a dataframe
eventdata <- data.frame(datetime = events, months = month_of_event)
# classify months into seasons
summer<-c(1,2,12)
fall<-c(3,4,5)
winter<-c(6,7,8)
spring<-c(9,10,11)
season.names <- rep("",12)
season.names[summer] <- "Summer"
season.names[fall] <- "Fall"
season.names[winter] <- "Winter"
season.names[spring] <- "Spring"
season.names
eventdata$season<-season.names[eventdata$months]
str(eventdata)
# Plot
ggplot(eventdata, aes(x = months, fill = season)) +
geom_histogram(breaks = seq(0,12, by=1), width = 4) +
coord_polar(start = 0) + theme_minimal() +
scale_fill_brewer() + ylab("Count") +
scale_x_continuous("", limits = c(0, 12), breaks = seq(0, 12), labels = seq(0,12))
Upvotes: 2
Views: 2281
Reputation: 24593
Following simple version works:
ggplot(eventdata, aes(x = factor(months), fill = season)) +
geom_histogram()+
coord_polar()
Upvotes: 5