我有一个有趣的问题,我需要制作一个刻面的直方图系列,我想按每个面板的降序排列。下面的代码复制了这个问题。
library(ggplot2)
set.seed(1)
nGroup = 10; nSample = 10
df <- data.frame(Group=rep(1:nSample,nGroup),
Category = factor(sample(LETTERS,
nGroup*nSample,
replace=TRUE),
levels=LETTERS),
Amount = runif(nGroup*nSample))
ggplot(df,aes(x=Category,y=Amount)) +
geom_bar(stat='identity') +
facet_wrap(~Group,scales='free_x') +
labs(title="Some Random Histogram with Facets")
产生以下输出:
我尝试了以下内容:
library(ggplot2)
set.seed(1)
nGroup = 10; nSample = 10
df <- data.frame(Group=rep(1:nSample,nGroup),
Category = factor(sample(LETTERS,
nGroup*nSample,
replace=TRUE),
levels=LETTERS),
Amount = runif(nGroup*nSample))
ggplot(df,aes(x=reorder(Category,-Amount),y=Amount)) +
geom_histogram(stat='identity') +
facet_wrap(~Group,scales='free_x') +
labs(title="Some Random Histogram with Facets")
这是一个小小的改进(见下文),但没有 - 它应该在哪里附近。
任何建议都会受到高度赞赏?我完全理解x轴标签在面板之间不对应,这对我的应用来说很好。
library(ggplot2)
set.seed(1)
nGroup = 10; nSample = 10
df <- data.frame(Group=factor(rep(1:nSample,nGroup)),
Category = factor(sample(LETTERS,
nGroup*nSample,
replace=TRUE),
levels=LETTERS),
Amount = runif(nGroup*nSample))
df <- ddply(df,c("Group","Category"),function(d){ data.frame(Amount=sum(d$Amount)) })
df$Interaction = interaction(df$Category,df$Group)
df$XLabel = as.character(df$Category)
ggplot(df,aes(x=reorder(Interaction,-Amount),y=Amount,fill=Amount)) +
geom_bar(stat='identity',color="black",width=1.0) +
scale_x_discrete(breaks=df$Interaction,labels=df$XLabel) +
facet_wrap(~Group,scales='free_x') +
theme_bw() + theme(legend.position=c(1,0),legend.justification=c(1,0)) +
theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust=0.5, size=6)) +
scale_fill_gradient(low="blue",high="red") +
labs(title="Some Random Histogram with Facets",x="Category")
根据需要产生以下内容:
答案 0 :(得分:1)
您可以在reorder
和interaction
之间使用groups
和Category
ggplot(df,aes(x=reorder(interaction(Category, Group), -Amount, sum),y=Amount)) +
geom_bar(stat='identity') +
facet_wrap(~Group,scales='free_x') +
labs(title="Some Random Histogram with Facets")