在将单独的图绘制在一起时自动调整轴限制

时间:2017-10-16 14:14:10

标签: r ggplot2 gridextra yaxis

我想在并排绘图的同时自动调整ggplot图。

library(ggplot2)
library(gridExtra)

set.seed(123)
freq <- sample(1:10, 7, replace = T)
labels <- c('AUS', 'NZ', 'ENG', 'SOC', 'PAK', 'SRI', 'IND')
value <- paste("i",1:10,sep='')

lab <- rep(unlist(lapply(1:length(freq), function(x) rep(labels[x],freq[x]))),2)
ival <- rep(unlist(lapply(1:length(freq), function(x) value[1:freq[x]])),2)

df <- data.frame(lab, ival, type=c(rep('Type1',42),rep('Type2',42)),val=runif(84,0,1))

绘制使用上述随机过程生成的数据。

plotUng <- ggplot(df, aes(x=ival, y=val, col = type, group = type)) + 
  geom_line() + 
  geom_point(aes(x=ival, y=val)) +
  facet_wrap( ~lab, ncol=3) + 
  theme(axis.text.x=element_text(angle=45, vjust=0.3)) + 
  scale_x_discrete(limits=paste('i',1:10,sep=''))

现在根据某些条件将数据分组到lab。现在我想基于分组数据生成新的图。

dfGrp <- df %>% mutate(lab = recode(lab, 'AUS' = 'A', 'NZ' = 'A', 'ENG' = 'A', 
                                    'SOC' = 'A', 'PAK' = 'B', 'SRI' = 'B')) %>% 
  group_by(lab, ival, type) %>% mutate(val = mean(val)-0.2) %>% ungroup() %>% distinct()

plotG <- ggplot(dfGrp, aes(x=ival, y=val, col = type, group = type)) + 
  geom_line() + 
  geom_point(aes(x=ival, y=val)) +
  facet_wrap( ~lab, ncol=3) + 
  theme(axis.text.x=element_text(angle=45, vjust=0.3)) + 
  scale_x_discrete(limits=paste('i',1:10,sep=''))

使用grid.arrange并排绘制上述两个图以进行比较。

grid.arrange(plotUng, plotG, ncol=2)

enter image description here

在手动检查上图后,调整y轴限制 plotUng 的范围比 plotG 更宽。因此,使用plotUng的限制调整plotG的限制为coord_cartesian(ylim = ggplot_build(plotUng)$layout$panel_ranges[[1]]$y.range)

grid.arrange(plotUng, plotG + coord_cartesian(ylim = ggplot_build(plotUng)$layout$panel_ranges[[1]]$y.range), ncol=2)

enter image description here

上图是预期的。是否有任何方法可以自动执行此操作(仅使用绘图对象)而无需手动检查,因为并不总是可以手动检查所有图并相应地调整轴限制?

1 个答案:

答案 0 :(得分:0)

您对const routes: Routes = [ { path: '', component: UserHomeComponent, }, { path: 'userDetails', component: UserDetailsComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class UserManagementRoutingModule { } 所做的工作可以实现自动化。但对我来说,比较几个图的最简单方法是找到要比较的所有对象的最小值和最大值,然后将这些值作为每个对象的ggplot_build()。例如:

coord_cartesian()

enter image description here

由于找到几列的极值很简单,这是我发现的最“自动化”的方式。

  

请注意,坐标问题仅发生在lim_y <- c( min(df$val, dfGrp$val), max(df$val, dfGrp$val) ) plotUng <- plotUng + coord_cartesian(ylim = lim_y) plotG <- plotG + coord_cartesian(ylim = lim_y) grid.arrange(plotUng, plotG, ncol=2)

中的y限制
相关问题