繁体   English   中英

R,ggplot2,多面直方图,降序,因子x轴标签

[英]R, ggplot2, facetted histogram, decending order, factor x-axis labels

我有一个有趣的问题,我需要生成一个多面的直方图序列,我想对每个面板按降序排列。 下面的代码复制了该问题。

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轴标签在面板之间不会对应,这对我的应用程序来说很好。


更新:修复标签。

Mamoun的答案就可以了,但是,对于那些有兴趣修复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")

根据需要产生以下内容:

示例3

您可以像这样使用groupsCategory之间的reorderinteraction

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM