R编程:如何控制分组堆积条形图中的顺序?

时间:2016-01-20 14:50:23

标签: r ggplot2

我有以下图表,我希望“InProcess”低于“调查”。我认为重新排序状态因素会做到这一点,但它所做的一切都会影响图例的打印顺序。你会如何做到这一点?

enter image description here

以下是创建此图表的代码和数据集。

数据:

Date    Identified  InProcess   Fixed   NotFixed    Duplicate
11/12/2015  22  43  10  5   8
11/19/2015  11  21  11  9   27
11/26/2015  24  10  10  4   13
12/3/2015   39  11  4   2   17
12/10/2015  36  11  11  8   8
12/17/2015  32  9   9   4   7
12/24/2015  20  6   4   12  13
12/31/2015  19  4   5   3   2
1/7/2016    21  3   5   4   2

plotgraph <- function() {
  require(ggplot2)
  require(reshape2)
  require(data.table)

  testdata <- read.table(header = TRUE, stringsAsFactors = FALSE, text = "Date    Identified  InProcess   Fixed   Inactionable    Duplicate
                       11/12/2015  22  43  10  5   8
                       11/19/2015  11  21  11  9   27
                       11/26/2015  24  10  10  4   13
                       12/3/2015   39  11  4   2   17
                       12/10/2015  36  11  11  8   8
                       12/17/2015  32  9   9   4   7
                       12/24/2015  20  6   4   12  13
                       12/31/2015  19  4   5   3   2
                       1/7/2016    21  3   5   4   2")
  setnames(testdata,c("Date","Investigating",   "InProcess",    "Fixed",    "Inactionable", "Duplicate"))
  testdata<-testdata[1:5,]

  testdata$Date <- as.Date(testdata$Date,format="%m/%d/%Y")
  df <- melt(testdata,id.vars="Date")
  df$group <- ''

  for (i in 1:nrow(df)) {
    if ((df$variable[i] == "Investigating") | (df$variable[i] == "InProcess")) {
      df$group[i] <- ".Open"
    }
    else {
      df$group[i] <- as.character("Closed")
    }
  }

  setnames(df,c("date","state","count","group"))
  df$state <- relevel(df$state,"Investigating")
  cols <-  c(  Investigating = "coral2",InProcess = "coral4",Fixed = "olivedrab4", Inactionable = "olivedrab3", Duplicate =  "olivedrab1")

  df<- transform(df, 
           state.ord  = factor(
             df$state,
             levels=c( 'Investigating','InProcess','Fixed','Inactionable','Duplicate' ),
             ordered =TRUE))


  a <- ggplot(df,aes(x=group,y=count,fill=state,order=state.ord)) + 
    geom_bar(stat="identity",position="stack",aes(fill=state.ord)) +
    facet_grid(~date) +
    scale_fill_manual(values=cols,name="") +
    xlab("") + ylab("Count of Issues")

  a
}

1 个答案:

答案 0 :(得分:0)

添加/修改此部分以获取正确的图表

df<- transform(df, 
           state.ord  = factor(
             df$state,
             levels=c('Duplicate','Inactionable','Fixed' ,'Investigating','InProcess' ),
             ordered =TRUE))

  df <- df[order(-xtfrm(df$state.ord)), ]
相关问题