【问题标题】:How to create stacked and grouped chart?如何创建堆叠和分组图表?
【发布时间】:2020-10-11 20:47:30
【问题描述】:

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

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

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

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

如何在 ggplot 中按组和堆栈制作条形图?我需要什么数据结构来实现它?

提前感谢您的建议!

【问题讨论】:

    标签: r stack grouping bar-chart


    【解决方案1】:

    您可以尝试这些选项中的任何一个,将您的数据重新整形为 long 并创建和附加变量,以便您可以识别类型。这里使用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() 并以智能方式放置标签。

    【讨论】:

    • 非常感谢您的代码和解释!这很好@Duck
    猜你喜欢
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2017-11-01
    • 2019-04-08
    • 2021-04-06
    相关资源
    最近更新 更多