如何在同一图中为多个变量获取几个水平条形图

时间:2018-08-02 15:18:18

标签: r ggplot2

我有几个分类变量,我需要根据其模态频率来绘制其水平条形图。例如,如果我想绘制变量INTERET_ENVIRONNEMENT的水平条形图,则知道其模态为:

> unique(DATABASE$INTERET_ENVIRONNEMENT)
[1] Beaucoup    Un peu      Pas du tout
Levels: Beaucoup Pas du tout Un peu 

然后使用上面的代码:

ords <- c("Beaucoup", "Un peu", "Pas du tout")

ggplot(DATABASE, aes(x = INTERET_ENVIRONNEMENT)) + 
  geom_bar(fill = "orange", width = 0.7) + 
  scale_x_discrete(limits = ords) +
  coord_flip() + 
  xlab("Storm Type") + ylab("Number of Observations")

我得到这个enter image description here

现在,我想添加所有其他类别变量,以在同一图中获得其水平条形图。 例如,如果我还要添加具有相同形式(“ Beaucoup”,“ Un peu”,“ Pas du tout”)的INTERET_COMPOSITION变量。

我尝试使用此代码

ggplot(DATABASE, aes(x = INTERET_ENVIRONNEMENT)) + 
  geom_bar(fill = "orange", width = 0.7) + 
  scale_x_discrete(limits = ords) +
  coord_flip() + 
  xlab("Storm Type") + ylab("Number of Observations")+
  facet_wrap(~INTERET_COMPOSITION)

但是,它没有提供所需的结果。

为了使我的示例具有可重复性,这是一个数据集,其中包含4个具有相同模式的类别变量:

structure(list(INTERET_COMPOSITION = structure(c(1L, 1L, 1L, 
3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 3L, 3L, 1L, 
1L, 1L, 1L, 3L, 1L, 3L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Beaucoup", 
"Pas du tout", "Un peu"), class = "factor"), INTERET_ENVIRONNEMENT = structure(c(1L, 
3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 3L, 1L, 3L, 1L, 3L, 1L, 1L, 
1L, 1L, 1L, 3L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("Beaucoup", "Pas du tout", "Un peu"), class = "factor"), 
    INTERET_ORIGINE_GEO = structure(c(1L, 2L, 1L, 1L, 3L, 1L, 
    3L, 1L, 1L, 3L, 1L, 1L, 1L, 3L, 1L, 2L, 1L, 1L, 3L, 1L, 1L, 
    1L, 1L, 3L, 3L, 1L, 2L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    3L, 1L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 1L, 1L, 1L), .Label = c("Beaucoup", 
    "Pas du tout", "Un peu"), class = "factor"), INTERET_ALIM_NATURELLE = structure(c(1L, 
    3L, 3L, 1L, 3L, 1L, 1L, 1L, 3L, 1L, 1L, 3L, 1L, 1L, 1L, 2L, 
    3L, 3L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 1L, 3L, 1L, 1L, 3L, 1L, 
    1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L), .Label = c("Beaucoup", "Pas du tout", "Un peu"
    ), class = "factor")), .Names = c("INTERET_COMPOSITION", 
"INTERET_ENVIRONNEMENT", "INTERET_ORIGINE_GEO", "INTERET_ALIM_NATURELLE"
), row.names = c(1L, 2L, 3L, 5L, 9L, 13L, 14L, 16L, 18L, 19L, 
20L, 24L, 27L, 29L, 30L, 32L, 33L, 35L, 36L, 37L, 39L, 44L, 49L, 
51L, 52L, 53L, 55L, 56L, 61L, 62L, 63L, 65L, 66L, 67L, 71L, 74L, 
75L, 80L, 81L, 84L, 86L, 90L, 92L, 95L, 96L, 99L, 100L, 103L, 
104L, 107L), class = "data.frame")
> 

请,我应该如何在同一图中绘制其水平条形图?

1 个答案:

答案 0 :(得分:4)

您必须将数据从宽范围转换为长范围

library(tidyverse)
d %>% 
  gather(k, v) %>% 
  ggplot(aes(v)) + 
  geom_bar(fill = "orange", width = 0.7) + 
  coord_flip() + 
  facet_wrap(~k)

enter image description here