I am having problems getting the corrector order of factors within a barplot.
I have a dataset with three variables: Region
, Store.Type
, and Avg.Value
. Region
and Store.Type
are factor types and Avg.Value
is a numeric. I am using the ggplot2
plotting system in R in a bar chart format with the geom_bar()
function.
Desired result:
I want Supercenter to be the first category in the facet_grid()
followed by the Market, and Mart. Within each facet, I want Region
1-7 sorted by descending order by Avg.Value
.
Reproducible example:
There are 3 Store.Type
for every Region
making a total of 21 Avg.Value
observations. My original dataset is larger with >3k observations.
#Create dataset
#avg value
Avg.Value <- as.vector(as.numeric(1:21))
#Regions
ab <- c("Region 1","Region 2","Region 3", "Region 4", "Region 5", "Region 6", "Region 7")
b <- 3 # Or some other number
ab <- sapply(ab, function (x) rep(x,b))
Region <- as.vector(ab)
#Chains
Store.Type <- c("Supercenter", "Mart", "Market", "Supercenter", "Mart", "Market",
"Supercenter", "Mart", "Market", "Supercenter", "Mart", "Market",
"Supercenter", "Mart", "Market", "Supercenter", "Mart", "Market",
"Supercenter", "Mart", "Market")
#Combine dataset
avgRes <- data.frame(Avg.Value, Region, Store.Type)
#Graph
library(ggplot2)
ch <- ggplot(avgRes, aes(x = Region, y = Avg.Value))
cha <- ch + geom_bar(stat = "identity")
chan <- cha + facet_grid(. ~ Store.Type)
chang <- chan + theme(axis.text.x = element_text(angle = 90, hjust = 1))
chang + ggtitle("Chart")
Barchart:
EDIT: I also want a count legend with the blue shading.