如何创建堆叠和分组图表?

How to create stacked and grouped chart?

我正在尝试按月创建一个包含两列的条形图,每列堆叠在一起。对于每个月,第一列是视频访问总数,除以 vid_new 和 vid_return。第二列是 phone 访问的总数,除以 phone_charge 和 phone_nocharge。

我仍然无法并排正确显示条形图。此代码使用第二张图片中的数据帧,它计算单词“视频”和“phone”的实例,而不是计算第三张图片的计数列。

plot <- ggplot(data=new_df, aes(x=Month, y = count, fill = gen_type)) +
 geom_bar(stat = "identity", position = "dodge")

下面是我正在处理的数据的图片。我已将其转换为几种不同的形式以尝试新方法,但无法形成此图。

如何在 ggplot 中按组和堆栈制作条形图?我需要什么数据结构才能成功?

提前感谢您的建议!

您可以尝试这些选项中的任何一个,将您的数据重塑为长数据并创建额外的变量,以便您可以识别类型。这里的代码使用 tidyverse 函数:

library(ggplot2)
library(dplyr)
library(tidyr)
#Date
df <- data.frame(Month=c(rep('Mar',4),rep('Apr',4),rep('May',2)),
                 spec_type=c('vid_new','vid_return','phone_charge','phone_nocharge',
                             'vid_new','vid_return','phone_charge','phone_nocharge',
                             'vid_new','vid_return'),
                 Count=c(7,85,595,56,237,848,2958,274,205,1079))
#Plot 1
df %>% mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
  mutate(Dup=spec_type) %>%
  separate(Dup,c('Type','Class'),sep='_') %>% select(-Class) %>%
  ggplot(aes(x=Type,y=Count,fill=spec_type))+
  geom_bar(stat = 'identity',position = 'stack')+
  facet_wrap(.~Month,strip.position = 'bottom')+
  theme(strip.placement = 'outside',
        strip.background = element_blank())

输出:

或者这样:

#Plot 2
df %>% mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
  mutate(Dup=spec_type) %>%
  separate(Dup,c('Type','Class'),sep='_') %>% select(-Class) %>%
  ggplot(aes(x=Type,y=Count,fill=spec_type))+
  geom_bar(stat = 'identity',position = 'fill')+
  facet_wrap(.~Month,strip.position = 'bottom',scales = 'free')+
  theme(strip.placement = 'outside',
        strip.background = element_blank())

输出:

或者这样:

#Plot 3
df %>% mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
  mutate(Dup=spec_type) %>%
  separate(Dup,c('Type','Class'),sep='_') %>% select(-Class) %>%
  ggplot(aes(x=Type,y=Count,fill=spec_type))+
  geom_bar(stat = 'identity',position = position_dodge2(preserve = 'single'))+
  facet_wrap(.~Month,strip.position = 'bottom',scales = 'free')+
  theme(strip.placement = 'outside',
        strip.background = element_blank())

输出:

为了按月查看,您可以使用 facet_wrap() 并以智能方式放置标签。