代码之家  ›  专栏  ›  技术社区  ›  captcoma

将空条形图添加到百分比条形图中(由at的长数据生成)

  •  0
  • captcoma  · 技术社区  · 5 年前

    我想在柱状图中将特定项目作为空条添加到x轴上

    例如:

    # load packages
    library(reshape2)
    library(tidyverse)
    library(scales)
    
    
    #get data
    data(tips, package = "reshape2")
    
    tips
    
    # make plot
    myplot <- ggplot(tips, aes(day, group = sex)) + 
      geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + 
      scale_y_continuous(labels=scales::percent) +
      ylab("relative frequencies") +
      facet_grid(~sex)
    
    myplot
    

    现在我想添加缺失的工作日,作为空栏:

    missing_days <-c("Tue","Wed")
    

    enter image description here

    如果可能的话,我想保持“整洁”的长数据格式 tips (这样我仍然可以在 aes 命令。 在长数据格式中添加“空”项的诀窍是什么?

    0 回复  |  直到 5 年前
        1
  •  5
  •   Rui Barradas    5 年前

    以下代码将首先获取所有工作日,然后在不删除未使用级别的情况下绘制图表。

    tips$day <- as.character(tips$day)
    
    days_levels <- weekdays(Sys.Date() + 1:7, abbreviate = TRUE)
    fri <- grep("Fri", days_levels)
    days_levels <- c(days_levels[fri:length(days_levels)], days_levels[1:(fri - 1)])
    days_levels[days_levels == "Thu"] <- "Thur"
    tips$day <- factor(tips$day, levels = days_levels)
    
    # make plot
    myplot <- ggplot(tips, aes(day, group = sex)) + 
      geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + 
      scale_y_continuous(labels=scales::percent) +
      scale_x_discrete(drop = FALSE) +
      ylab("relative frequencies") +
      facet_grid(~sex)
    
    myplot
    

    enter image description here

        2
  •  2
  •   Khaynes    5 年前

    您可以简单地将天数添加到因子水平中:

    tips$day <- factor(tips$day, levels = c(attributes(tips$day)$levels, "Tues", "Wed"))
    

    并将以下内容添加到ggplot中:

    scale_x_discrete(drop = FALSE)
    

    完整代码

    # load packages
    library(reshape2)
    library(tidyverse)
    library(scales)
    
    
    # get data
    data(tips, package = "reshape2")
    
    tips
    
    tips$day <- factor(tips$day, levels = c(attributes(tips$day)$levels, "Tues", "Wed"))
    
    # make plot
    myplot <- ggplot(tips, aes(day, group = sex)) + 
      geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + 
      scale_y_continuous(labels=scales::percent) +
      ylab("relative frequencies") +
      scale_x_discrete(drop = FALSE) +
      facet_grid(~sex)
    
    myplot
    

    输出:

    enter image description here

    推荐文章