How to order multiple charts via facet_wrap in ggplot2
I have a dataset like the following and I have about 1 million rows:
orderid prodid priceperitem date category_eng
3010419 2 62420 18.90 2014-10-09 roll toliet paper
I am currently plotting these images using both priceperitem
the y-axis and date
the x-axis. I also ordered these lines based on the CV of their products over time. I have summarized these results in another dataset such as the following:
prodid mean count sd cv
424657 12.7124 5541.0000 10.239 80.54999886
158726193 23.7751 1231.0000 17.7567 74.68621596
And I used the following code to get scatterplots at the same time:
ggplot(Roll50.last, aes(x=date, y=priceperitem)) + geom_point() + facet_wrap(~prodid)
But I want to order graphics based on the CV of these products, which I have summarized in another data.frame file. I am wondering if there is a way that might allow me to indicate that I want to order the panel plots in order of value in another dataframe.
Below are some small sample data. Basically, the idea is to get the cv price of different products that = sd / mean. And I want to plot these scatterplots of these products in cv order from highest to lowest.
#generate reproducible example
id = c(1: 3)
date = seq(as.Date("2011-3-1"), as.Date("2011-6-8"), by="days")
id = rep(c(1,2,3,4),each=25)
set.seed(01)
id = sample(id)
price = rep(c(1:20), each = 5)
price = sample(price)
data = data.frame(date, id, price)
source to share
You can convert prodid
to coefficient and order the factor categories based on the size of the coefficient of variation. For example, suppose your dataframe with cv values is called cv
. Then, to order prodid
into values cv
:
Roll50.last$prodid = factor(Roll50.last$prodid,
levels = cv$prodid[order(cv$cv, decreasing=TRUE)])
Now when you plot the data, the faces prodid
will be ordered by decreasing the size cv
.
source to share