Using qplot + facet_wrap, where the plots are ordered by one variable and labeled by another

StackOverflow https://stackoverflow.com/questions/21322089

  •  02-10-2022
  •  | 
  •  

Question

I have a dataset as follows:

Date         State     Count   mean
1994-01-05   Alabama   408     581.333
1994-01-06   Alabama   784     581.333
1994-02-08   Alabama   552     581.333
1994-01-05   Arizona   385     759.666
1994-01-06   Arizona   1845    759.666
1994-02-08   Arizona   49      759.666
1994-01-05   Alaska    1067    3224.666
1994-01-06   Alaska    36      3224.666
1994-02-08   Alaska    8571    3224.666

where there are "counts" for an ordered set of dates for each of the fifty states. The mean of the counts for each state is how the states are ordered.

I would like to make a plot with subplots of the 50 states, with the count as the y-axis and the date as the x-axis. I would like the subplots to be arranged by increasing mean counts (top left --> bottom right). However, I would like the title of each subplot to include the State (whether or not its mean value is also included does not matter much).

I tried:

qplot(Date, Count, data =dataset) + facet_wrap(~mean,nrow=7) 

This led to an almost perfect plot. It consists of the fifty subplots, with the correct axes, and in increasing order of their mean counts. However, the title of each subplot is not the state, but the mean of the state.

Any advice would be appreciated!!

Was it helpful?

Solution

At the moment you cannot pass expressions to facet_wrap, so one approach to create a factor column with the levels in the order you wish. The idiomatic R approach is to use reorder

# create factor
dataset$State_lab <- with(dataset, reorder(x=State,X=mean))
# your plot
qplot(Date,Count,data=dataset) + facet_wrap(~State_lab)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top