我有一张包含以下数据的表格
marks cut but xut
1 49 51 67
2 53 47 76
3 54 46 67
4 54 46 56
5 55 45 65
6 55 45 75
7 55 45 45
8 55 45 33
9 55 45 43
10 56 45 53
11 56 45 23
12 56 44 78
13 56 44 45
当我绘制图形时,我得到的图例为切割但是xut,我希望图例为xut但是切割,即我想重新排序图例并以我需要的方式呈现它们
下面是我实施的代码
install.packages("plyr")
install.packages("ggplot2")
install.packages("reshape2")
library("plyr")
library("reshape2")
library("ggplot2")
data=read.csv("data.csv")
attach(data)
data$marks <- factor(data$marks, levels
= data$marks[order(data$cut)])
c.data=melt(data, id.var="marks")
n.data = ddply(c.data,.(marks), transform, pos = cumsum(value) - 0.5*value)
n.data <- transform(n.data,variable = factor(levels = c("xut", "but", "cut")))
plot = ggplot(d.data, aes(x = marks, y = value)) + geom_bar(stat = "identity",mapping = aes(x = value, fill = variable)) + scale_y_continuous( breaks=seq(0,100, by = 10))+geom_text(aes(label = value, y = pos), size = 3, face="bold", colour="white") + scale_fill_manual(values=c("455555","333333","335566")) + theme(axis.line = element_line(),axis.text.x=element_text(angle=60,hjust=1,colour="white"),axis.text.y=element_text(colour="white"),axis.title.x = element_blank(),axis.title.y = element_blank(),panel.background = element_blank(),axis.ticks=element_blank()) + labs(fill="")+coord_cartesian(ylim=c(0,100)) + theme(legend.position = "bottom", legend.direction = "horizontal")
答案 0 :(得分:4)
使用长数据或融合版数据中的组对变量的级别重新排序。例如,使用您的数据
foo <- read.table(text="marks cut but xut
1 49 51 67
2 53 47 76
3 54 46 67
4 54 46 56
5 55 45 65
6 55 45 75
7 55 45 45
8 55 45 33
9 55 45 43
10 56 45 53
11 56 45 23
12 56 44 78
13 56 44 45", header = TRUE)
将其融入合适的格式
require(reshape2)
require(ggplot2)
bar <- melt(foo, id = "marks")
> head(bar)
marks variable value
1 1 cut 49
2 2 cut 53
3 3 cut 54
4 4 cut 54
5 5 cut 55
6 6 cut 55
然后在包含组标签的variable
因子上设置级别
bar <- transform(bar,
variable = factor(variable, levels = c("xut", "but", "cut")))
然后绘制
ggplot(bar) + geom_bar(mapping = aes(x = value, fill = variable))
由于您没有显示任何绘图代码,我猜测您的实际绘图代码是什么样的,但如上所示,至少订购是您想要的......