-3

我有一张包含以下数据的表格

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

当我绘制图表时,我得到的图例为 cut but xut ,我希望图例为 xut but 和 cut ,即我想重新排序图例并以我需要的方式呈现它们

下面是我实现的代码

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") 
4

1 回答 1

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))

由于您没有显示任何绘图代码,我猜测您的实际绘图代码是什么样的,但如上所示,至少排序是您想要的......

于 2013-07-30T16:23:23.050 回答