[英]R Programming: How do I control the order in a grouped stacked bar chart?
I have the following graph and I would like "InProcess" to be below "Investigating". 我有以下图形,我希望“处理中”位于“调查”下方。 I thought reordering the state factor would do it, but all it does is affect the order the legend is printed. 我认为对状态因子进行重新排序可以做到,但是它所做的一切都会影响图例的打印顺序。 How would you accomplish this? 您将如何实现?
Here is the code and dataset that creates this graph. 这是创建此图的代码和数据集。
Data: 数据:
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
}
This section was added/modified to get the correct graph 添加/修改了此部分以获得正确的图形
df<- transform(df,
state.ord = factor(
df$state,
levels=c('Duplicate','Inactionable','Fixed' ,'Investigating','InProcess' ),
ordered =TRUE))
df <- df[order(-xtfrm(df$state.ord)), ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.