r - ggplot2:为条形图的构面布局中的行指定不同的比例

标签 r ggplot2 facet 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)

现在正在绘制自己:
#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")

第一个和第二个变体的结果如下:

enter image description here

在这两个例子中,我们要么对所有图都有自由尺度,要么对所有图都有固定尺度。同时,第一行(前 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")

和 - 惊喜:尺度的问题解决了,但是,我得到两组空条,整个数据再次延伸到一个长条上:

enter image description here

所有发现的手册页和手册(通常使用 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")

resulting plot

注意:基于这个可重复的例子,我假设你所有的图都已经在 0 处共享了一个共同的 ymin。如果不是这种情况,只需为 min.height 创建另一个虚拟变量并添加另一个 geom_blank到你的 ggplot。

关于r - ggplot2:为条形图的构面布局中的行指定不同的比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45684747/

相关文章:

R:如何读取带有 data.table::fread 的 CSV 文件,其中逗号为小数,点为千位分隔符 ="."

r - purrr 中的部分难题

r - ggplot geom_text字体大小控制

r - Ggplot2 绘制方面子集的均值而不是全局均值

r - 您在R中进行编程时会使用哪些最佳实践?

r - 在 R 中绘制子集 os 子集

r - 根据窗口大小调整绘图形状

r - 使用 stat_summary 自动调整 ylim

solr - 如何在SolrJ中设置facet方法?

r - 将 x 和 y 轴添加到所有 facet_wrap