簡體   English   中英

通過屬性計數重新排列構面序列

[英]Re-order the sequence of facet by the count of attribute

我想按2016年總數重新排列構面序列。 有什么辦法嗎?

以下是我的原始代碼:

library(ggplot2)
Dincident <-read.table("C:/Users/lionel.lee/Documents/Dincident.csv", header = TRUE, sep = ",")
head(Dincident)
d <- Dincident
d_bg <- d[, -4]  
ggplot(d,aes(Month,fill=PDline)) +
  geom_bar(data=d_bg,fill="gray") +
  geom_bar()+
  facet_grid(Year~PDline)+  
  scale_y_continuous(limit = c(0, 8),breaks=c(1,2,3,4,5,6,7,8)) +
  scale_x_continuous(limit = c(0, 12),breaks=c(3,6,9,12))   

預期產量:

在此處輸入圖片說明

您可以創建人工ord列,該列將指示排序的總數取決於YearPDline ,例如1表示給定Year最大計數。 然后,您將可以對Yearord使用facet。 請參見下面的代碼:

library(ggplot2)

# data.simulation
set.seed(123)
n <- 200
Dincident <- data.frame(
  Month = sample(1:12, n, replace = TRUE),
  Year = sample(2015:2016, n, replace = TRUE),
  PDline = sample(LETTERS[1:3], n , replace = TRUE),
  Misc = 1:n
)
d <- Dincident
d_bg <- d[, - 4]
x <- as.data.frame(table(Dincident$Year, d$PDline))
x1 <- lapply(
  X = split(x, x$Var1), 
  function(l) {
    l$y <- interaction(l$Var1, l$Var2)
    l <- l[order(l$Freq, decreasing = TRUE), ]
    l$ord <- 1:nrow(l)
    l
  }
)

x2 <- do.call(rbind, x1)
colnames(x2)[1:2] <- c("Year", "PDline")

d <- merge(d, x2)
# data plotting
ggplot(d, aes(Month, fill = PDline)) +
  geom_bar(data = d_bg, fill = "gray") +
  geom_bar() +
  facet_grid(Year ~ ord, labeller = label_context)+  
  scale_y_continuous(limit = c(0, 8), breaks = 1:8) +
  scale_x_continuous(limit = c(0, 12), breaks = (1:4) * 3)   
x2

輸出(每計數數量YearPDline

       Year PDline Freq      y ord
2015.5 2015      C   43 2015.C   1
2015.1 2015      A   35 2015.A   2
2015.3 2015      B   30 2015.B   3
2016.4 2016      B   33 2016.B   1
2016.2 2016      A   32 2016.A   2
2016.6 2016      C   27 2016.C   3

圖形:

圖形

暫無
暫無

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

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