通过属性计数重新排序构面序列

时间:2016-08-16 15:45:53

标签: r sorting ggplot2

我想按照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))   

预期产出:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以创建人为的ord列,该列将指示已排序的总数取决于YearPDline,例如1-表示给定Year的最大计数。然后,您将可以对Yearord使用构面。请参见下面的代码:

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

图:

graph