Hanna
Hanna

Reputation: 69

Facet Wrap by Month (Numeric instead of Alpha)

I have yet again one minor struggle that I cannot seem to figure out myself. I need to create a graph facet wrapped by month. But when I do that, I get this. As you can see, the months are in alphabetical, rather than numerical order. I'm not entirely sure how to remedy this problem. I'll attach the code for the graph itself and the month column.

map.dat <- map_data(map(database= "world", ylim=c(15,90), xlim=c(-180, -40), fill = TRUE))
ggplot(map.dat) +
  geom_polygon(aes(x=long, y=lat, group=group, fill=NULL)) +
  geom_path(data = subset(basindf2, year >= 1980 & 2010 >= year), aes(x = latitude, y = longitude, col = wind, group = factor(id))) +
  scale_colour_gradientn(colours = brewer.pal(9, 'Reds')[c(2,7,8,9)]) +
  xlab('') + scale_x_continuous(breaks = NULL) +
  ylab('') + scale_y_continuous(breaks = NULL) +
  ggtitle('Storm Trajectory (1980-2010)') +
  theme_bw() + theme(plot.title = element_text(size = 20, face="bold"), panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
  facet_wrap(~month)

Month Column Cleaning:

monthnames <- c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
monthraw <- as.numeric(str_extract(str_extract(rawdfNA$V7, '-..-'), '\\d\\d'))
month <- monthnames[monthraw]

So I created a specific column for the monthnames, extracted the months (monthsraw) from the original dataset and then got the month by selecting the names by the monthraw number.

Upvotes: 0

Views: 2384

Answers (1)

eipi10
eipi10

Reputation: 93821

You need to turn month into a factor with the month names ordered properly. So, if your month variable is map.dat$month you would do:

map.dat$month = factor(map.dat$month, levels=month.name)

month.name is a built-in object in R, so you don't need to create your own. factor turns month into a categorical variable, with the categories ordered based on the ordering listed in levels.

Upvotes: 2

Related Questions