如何将ggplot用于多行成一个绘图图形

问题描述

说实话,对于R专家来说,这是一个愚蠢而简单的问题。 但是,我已经有几个小时的问题了,还没有真正提出解决方案...

我有一项调查的数据,该调查询问有人是否已经使用语音助手(1 =正在使用,2 =未使用;因素)以及他们希望如何与系统通信(1 =将使用,0 =将不使用;数字)。由于交流问题可能有多种选择,因此我将答案分为几列。

#row Assistant Touchdisplay Mobile Voice
   1         1            0      1     1
   2         2            1      0     0
   3         1            1      1     1
   4         1            1      0     1     

现在,我想展示已经使用语音助手的人和未使用语音助手的人如何回答。

我尝试过:

ggplot(data) + geom_bar(aes(Touchdisplay==1,fill = Assistent),position = "dodge")

enter image description here

这几乎是我所需要的。但是,只有右侧(TRUE)不仅适用于触摸显示,而且适用于一张绘图中的所有其他方法

对于R专家来说,我敢肯定这很容易,并且我已经尝试了所有可以想到的方法,但是我目前缺少解决该问题的起点...

解决方法

我想您可能正在寻找这个?通常,您需要首先调整数据的形状:

data %>% 
  pivot_longer(cols = -Assistant) %>% 
  filter(value != 0) %>% 
  ggplot(aes(x = name,fill = factor(Assistant))) +
  geom_bar(position = position_dodge(preserve = 'single'))

enter image description here

,

我建议这样做:

library(tidyverse)
#Data
data <- structure(list(Assistant = c(1L,2L,1L,1L),Touchdisplay = c(0L,Mobile = c(1L,0L,0L),Voice = c(1L,1L)),row.names = c(NA,-4L),class = "data.frame")

代码:

data %>% pivot_longer(cols = -Assistant) %>% filter(value!=0) %>%
  group_by(Assistant,name) %>% summarise(val=sum(value)) %>%
  filter(name=='Touchdisplay') %>%
  ggplot()+
  geom_bar(stat = 'identity',aes(x=name,y=val,fill=factor(Assistant)),position=position_dodge())

输出:

enter image description here

通过这种方式,您还可以添加其他设备来更改代码filter(name=='Touchdisplay')

data %>% pivot_longer(cols = -Assistant) %>% filter(value!=0) %>%
  group_by(Assistant,name) %>% summarise(val=sum(value)) %>%
  ggplot()+
  geom_bar(stat = 'identity',position=position_dodge())

输出:

enter image description here

,

我认为OP希望在过滤Assistant==1之后只为每个类别绘制1,所以也许这就是您想要的?

首先,一些数据:

set.seed(22447)
data <- data.frame(Assistant=factor(sample(1:2,size=100,replace=T)),Touchdisplay=sample(0:1,replace=T),Mobile=sample(0:1,Voice=sample(0:1,replace=T))

使用以下示例数据,您的原始图将是这样:

ggplot(data) + geom_bar(aes(Touchdisplay==1,fill = Assistant),position = "dodge")

enter image description here

现在进行过滤,轮换使用更长的时间并进行总结:

ds <- data %>% filter(Assistant==1) %>% pivot_longer(-Assistant) %>% 
  group_by(name) %>% summarize(total=sum(value))

ds

summary的输出

        # A tibble: 3 x 2
      name         total
      <chr>        <int>
    1 Mobile          26
    2 Touchdisplay    26
    3 Voice           19

使用geom_col()来对1进行加密:

ggplot(ds) + geom_col(aes(name,total))

enter image description here