7

我正在尝试使用 ggplot2 制作更好的 R 基础图版本。不仅有一个共同的传说,还因为我喜欢 ggplot2 的样式和自定义。我的数据由 3 个单独的数据集组成,这些数据集包含针对几种(但不同)治疗的相同两组观察结果。因此,我想在 1 个图形中生成 3 个单独的图,它们有一个共同的图例,但具有不同的因子水平。为了说明我的观点,这里的第一张图片是我到目前为止用 R 基础生成的: r 基图最近的图实现

我尝试使用与我的数据具有完全相同结构的虚拟数据生成 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()

这给了我以下不良结果。 ggplot2 图像失败

我知道堆栈溢出主题Removing Unused Factors from a Facet in ggplot2How can I remove empty factors from a ggplot2 facets?但是,它们不处理我在这里尝试实现的聚集条形图,我觉得它们是问题所在,但是现在不知道如何解决它。欢迎所有指针。

4

1 回答 1

9

为了说明我的评论:

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

在此处输入图像描述

请注意,如果您添加coord_flip并切换到free_y您会收到关于不使用某些类型的自由秤的特定错误coord_flip,这是您问题的根源。

于 2013-04-08T20:11:59.647 回答