簡體   English   中英

將空條添加到(百分比)條形圖(從長數據 fromat 生成)

[英]Add empty bars to a (percentage) barplot (generated from long data fromat)

我想將特定項目作為條形圖中的空條添加到 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")

在此處輸入圖片說明

如果可能的話,我想keetp的“整潔”長數據的格式tips (這樣我還可以使用其他變量在aes指令。這是什么把戲加上“空”的項目,以長期的數據格式?

以下代碼將首先獲取所有工作日,然后在不刪除未使用級別的情況下繪制圖形。

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

在此處輸入圖片說明

您可以簡單地將天數添加到您的因子水平:

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

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM