我在条形图中获取因子的校正器顺序时遇到问题。
我有一个包含三个变量的数据集:Region
,Store.Type
和Avg.Value
。 Region
和Store.Type
是因素类型,Avg.Value
是数字。我在R中使用ggplot2
绘图系统以条形图格式使用geom_bar()
函数。
期望的结果:
我希望Supercenter成为facet_grid()
中的第一个类别,其次是Market和Mart。在每个方面中,我希望Region
1-7按Avg.Value
的降序排序。
可重复的示例:
每Store.Type
有3个Region
,总共有21 Avg.Value
次观察。我的原始数据集较大,观察值> 3k。
#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:
编辑:我还想要一个带有蓝色阴影的计数图例。
答案 0 :(得分:2)
我做的第一件事是翻转数据集中的第二个范围, 否则这些地区总是在1到7的顺序,你无法判断它是否有效。
#Create dataset avg value
Avg.Value <- as.vector(as.numeric(c(1:7,14:8,15: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)
然后我们需要重新排序avgRes $ Store.Type
的级别avgRes$Store.Type <- factor(avgRes$Store.Type, levels = c("Supercenter", "Market", "Mart"))
下一个问题是ggplot不能为每个方面拆分Region的顺序,所以我们必须添加一个唯一的顺序变量。之后,我们可以使用该变量重新排序。这取自here的答案。
avgRes$ordvar <- paste(avgRes$Store.Type,avgRes$Region,sep="_")
#Graph
library(ggplot2)
ch <- ggplot(avgRes, aes(x = reorder(ordvar,Avg.Value), y = Avg.Value)) # reorder ordvar by value
cha <- ch + geom_bar(stat = "identity")
chan <- cha + facet_grid(. ~ Store.Type, scale="free_x") #added "free_x", or you will have a lot of blank values in your plot
chang <- chan + theme(axis.text.x = element_text(angle = 90, hjust = 1))
chang + ggtitle("Chart")
请注意,标签现在是Store.Type_Region。 如果这让您感到困扰,您可以找到here如何使用函数修复它。