ast*_*rsk 5 r facet ggplot2 facet-wrap facet-grid
我的数据在包中ggplot2通过具有多个(~10)个面的条形图进行可视化。我想首先将这些方面分成几行。我可以使用函数facet_grid()或facet_wrap()来实现此目的。在此处的最小示例数据中,我在两行 (4x2) 中构建了 8 个面。但是,我需要调整不同方面的比例,即:第一行包含小比例的数据,第二行的值更大。因此,我需要对第一行中的所有数据使用相同的比例,以便沿行比较它们,并为第二行使用另一个比例。
这是最小的示例和可能的解决方案。
#loading necessary libraries and example data
library(dplyr)
library(tidyr)
library(ggplot2)
trial.facets<-read.csv(text="period,xx,yy
A,2,3
B,1.5,2.5
C,3.2,0.5
D,2.5,1.5
E,11,13
F,16,14
G,8,5
H,5,4")
#arranging data to long format with omission of the "period" variable
trial.facets.tidied<-trial.facets %>% gather(key=newvar,value=newvalue,-period)
Run Code Online (Sandbox Code Playgroud)
现在正在策划自己:
#First variant
ggplot(trial.facets.tidied,aes(x=newvar,y=newvalue,position="dodge"))+geom_bar(stat ="identity") +facet_grid(.~period)
#Second variant:
ggplot(trial.facets.tidied,aes(x=newvar,y=newvalue,position="dodge"))+geom_bar(stat ="identity") +facet_wrap(~period,nrow=2,scales="free")
Run Code Online (Sandbox Code Playgroud)
第一个和第二个变体的结果如下:
在这两个示例中,我们要么对所有图形使用自由比例,要么对所有图形使用固定比例。同时,第一行(前 4 个面)需要稍微缩放到 5,第二行需要缩放到 15。
作为使用facet_grid()函数的解决方案,我可以添加一个假变量“row”,它指定相应的字母应该属于哪一行。新数据集 Trial.facets.row(仅显示三行)如下所示:
period,xx,yy,row
C,3.2,0.5,1
D,2.5,1.5,1
E,11,13,2
Run Code Online (Sandbox Code Playgroud)
然后我可以将相同的重新排列为长格式,省略变量“句点”和“行”:
trial.facets.tidied.2<-trial.facets.row %>% gather(key=newvar,value=newvalue,-period,-row)
Run Code Online (Sandbox Code Playgroud)
然后,我沿着变量“行”和“周期”排列面,希望使用该选项scales="free_y"仅跨行调整比例:
ggplot(trial.facets.tidied.2,aes(x=newvar,y=newvalue,position="dodge"))+geom_bar(stat ="identity") +facet_grid(row~period,scales="free_y")
Run Code Online (Sandbox Code Playgroud)
并且 - 惊喜:尺度问题得到了解决,但是,我得到了两组空条,并且整个数据再次延伸到一条长条上:
所有发现的手册页和手册(通常使用 mpg 和 mtcars 数据集)都没有考虑此类不需要的或虚拟数据的情况
我结合使用了第一种方法 ( facet_wrap) 和第二种方法(利用不同行的虚拟变量):
# create fake variable "row"
trial.facets.row <- trial.facets %>% mutate(row = ifelse(period %in% c("A", "B", "C", "D"), 1, 2))
# rearrange to long format
trial.facets.tidied.2<-trial.facets.row %>% gather(key=newvar,value=newvalue,-period,-row)
# specify the maximum height for each row
trial.facets.tidied.3<-trial.facets.tidied.2 %>%
group_by(row) %>%
mutate(max.height = max(newvalue)) %>%
ungroup()
ggplot(trial.facets.tidied.3,
aes(x=newvar, y=newvalue,position="dodge"))+
geom_bar(stat = "identity") +
geom_blank(aes(y=max.height)) + # add blank geom to force facets on the same row to the same height
facet_wrap(~period,nrow=2,scales="free")
Run Code Online (Sandbox Code Playgroud)
注意:基于这个可重现的示例,我假设您的所有绘图已经共享一个共同的 ymin 为 0。如果情况并非如此,只需为 min.height 创建另一个虚拟变量并将另一个虚拟变量添加geom_blank到您的 ggplot 中。