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)
现在绘制自己:
#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")
第一个和第二个变体的结果如下:
在这两个示例中,我们要么为所有图设置了自由比例,要么为所有图设置了固定比例。同时,第一行(前 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
然后我可以将相同的重新排列为长格式,省略变量“句点”和“行”:
trial.facets.tidied.2<-trial.facets.row %>% gather(key=newvar,value=newvalue,-period,-row)
然后我沿着变量“row”和“period”排列构面,希望使用该选项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")
并且 - 惊喜:比例的问题得到了解决,但是,我得到了两组空条,整个数据再次延伸到一条长条上:
所有发现的手册页和手册(通常使用 mpg 和 mtcars 数据集)都没有考虑这种不需要或虚拟数据的情况