[英]Remove empty factors from clustered bargraph in ggplot2 with multiple facets
I am trying to make a better version of an R base plot with ggplot2. 我正在尝试使用ggplot2制作更好的R基础图。 Not only to have a common legend but also because I like the ggplot2 styles and customization.
不仅有一个共同的传奇,而且因为我喜欢ggplot2样式和自定义。 My data consists of 3 seperate datasets that contain the same two groups of observations for several (but different) treatments.
我的数据由3个单独的数据集组成,这些数据集包含几组(但不同)治疗的相同的两组观察结果。 Hence I want to generate 3 separate plots in 1 graph with a common legend however with different factor levels.
因此,我想在1个图中生成3个单独的图,但是具有不同的因子水平。 To illustrate my point the first image here is what I have generated with R base so far:
为了说明我的观点,这里的第一个图像是我到目前为止用R base生成的图像:
I tried to generate a ggplot2 plot with dummy data that has exactly the same structure as my data: 我尝试使用与我的数据具有完全相同结构的伪数据生成ggplot2图:
foo<-data.frame(c(letters,letters),c(rep('T1',26),rep('T2',26)),
runif(52),rep(c(rep('Ori1',12),rep('Ori2',8),rep('ori3',6)),2))
names(foo)<-c('Treatment','Type','Count','Origin')
a<-ggplot(foo,aes(x = factor(Treatment),y = Count))
a+ facet_grid(Origin~., scales="free_y", space="free") +
geom_bar(stat="identity",aes(fill=factor(foo$Type)),position="dodge")
+theme_bw()+theme(axis.text.x=element_text(angle=60,hjust=1))+coord_flip()
Which gives me the following undesirable result. 这给了我以下不良后果。
I am aware of the stack overflow topics Removing Unused Factors from a Facet in ggplot2 and How can I remove empty factors from ggplot2 facets? 我知道堆栈溢出主题从ggplot2中的Facet中删除未使用的因子以及如何从ggplot2 facets中删除空因子? however, they do not deal with the clustered bar graphs I try to realise here and I feel they are the problem, however do not now how to solve it.
但是,他们没有处理我试图在这里实现的聚类条形图,我觉得它们是问题,但现在不知道如何解决它。 All pointers are welcome.
欢迎所有指针。
To illustrate my comment: 为了说明我的评论:
a<-ggplot(foo,aes(x = factor(Treatment),y = Count))
a+ facet_wrap(~Origin, scales="free_x") +
geom_bar(stat="identity",aes(fill=factor(Type)),position="dodge") +
theme_bw() +
theme(axis.text.x=element_text(angle=60,hjust=1))
Note that if you add coord_flip
and switch to free_y
you get a specific error about coord_flip
not working with some types of free scales, which is the source of you problem. 请注意,如果您添加
coord_flip
并切换到free_y
则会收到有关coord_flip
的特定错误,该错误coord_flip
用于某些类型的自由缩放,这是您遇到问题的根源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.