2016-07-04 30 views
3

我试图一次性绘制多个因子列,使用ggplot2作为绘图引擎。如何用ggplot绘制多个因子列?

绘制多个指标列是直截了当:

library(ggplot2) 
library(dplyr) # dplyr 0.5.0 select_if 
library(purrr) 
data(diamonds) 


diamonds %>% 
    select_if(is.numeric) %>% 
    gather %>% 
    ggplot(aes(x = value)) + 
    geom_histogram() + 
    facet_wrap(~key) 

plot multiple quantitative variables

不过,我没有成功,在一杆绘制多个因素(定性)列。我想以编程方式选择列,即,而不是直接命名它们。

我想这一点,但它确实产生一个合理的结果:

diamonds %>% 
    select_if(is.factor) %>% 
    gather %>% 
    ggplot(aes(x = value)) + geom_bar() + 
    facet_wrap(~key) + 
    coord_flip() 

enter image description here

我认为有可能沿着这些路线的解决方案:

diamonds %>% 
    select_if(is.factor) %>% 
    ggplot(aes(x = .[[1]])) + geom_bar() 

在哪里.[[1]]应该由一些列占位符替换(所以在这里我直接将该列命名为列,可以避免,因为我在现实中有很多列)。

for循环可能会完成这项工作,但我想用dplyr来达到目的。

+1

你能否解释一下你会考虑一个明智的结果,即你的第二个数字与你想要的输出有什么不同?主要问题是每个绘图没有自己的Y轴(因此按字母顺序排序非常没有意义)? – mkt

+1

#mkt,感谢您的评论,#Axeman有一个好主意,那正是我在寻找的 –

回答

3

这里的诀窍是在您的facet调用中使用scales = free。例如:

diamonds %>% 
    select_if(is.factor) %>% 
    gather %>% 
    ggplot(aes(x = value)) + geom_bar() + 
    facet_wrap(~key, scales = 'free') + 
    theme_bw() + 
    theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) 

enter image description here

不幸的是免费体重秤和coord_flip没有发挥好。您可以使用the ggstance package中的geom_barh。或者,您可以在每列上使用lapply以获取ggplot对象的列表,并使用cowplot包将其拼接成一个图形。

+0

谢谢!这是有帮助的 –

+0

它刚刚出现在我脑海里,'lapply'也可能是一种方式,可能更容易与'coord_flip'一起玩@ Axeman –

1

也许比@Axeman那么优雅,而且工作和合作与coord_flip

library(gridExtra) 


gg_bar <- function(x, ...){ 
    { 
    ggplot(data_frame(x), aes(x = x)) + 
     geom_bar() + 
     coord_flip() 
    } 
} 

diamonds %>% 
    select_if(negate(is.numeric)) %>% 
    lapply(., function(x) gg_bar(x)) -> gg_bar_list 

do.call(grid.arrange, gg_bar_list) 

enter image description here

然而,变量( “X”)不显示的名字,这不是太美了。

+0

请参阅['cowplot :: plot_grid'](https://cran.r-project .org/web/packages/cowplot/vignettes/introduction.html)而不是'grid.arrange'来执行自动对齐和子图注记。您可以将注释用作变量标签,而不显示y轴标签。 – Axeman