R 按数据框中的最终值对图例进行排序

R 按数据框中的最终值对图例进行排序,r,ggplot2,R,Ggplot2,我想重新排列图例中的元素,因为它们在GGR绘图中从上到下显示。也就是说:我希望通过比较最右边点X轴点的Y值来确定顺序。在下面的数据中,我希望从顶部读取图例:bush、foo、baz、bar 更新:在@alexwhan评论之后,我将数据添加到脚本中 更新2:多亏了@thomas kern on#R(bosie)irc.freenode,这正是我所希望的。诀窍是将两者相加,即 scale_linetype_discrete(breaks = ord$Variant) + scale_shape_d

我想重新排列图例中的元素,因为它们在GGR绘图中从上到下显示。也就是说:我希望通过比较最右边点X轴点的Y值来确定顺序。在下面的数据中,我希望从顶部读取图例:bush、foo、baz、bar

更新:在@alexwhan评论之后,我将数据添加到脚本中

更新2:多亏了@thomas kern on#R(bosie)irc.freenode,这正是我所希望的。诀窍是将两者相加,即

 scale_linetype_discrete(breaks = ord$Variant) + scale_shape_discrete(breaks = ord$Variant)
这是我的简历:

library(plyr)
library(ggplot2)
require(grid)

args <- commandArgs(trailingOnly = TRUE)

lines <- "
X,Variant,Y
1,foo,123
1,bar,134
1,baz,135
1,bush,136
2,foo,221
2,bar,104
2,baz,155
2,bush,336
"

con <- textConnection(lines)
DF <- read.csv(con, header=TRUE)
close(con)
cdata <- ddply(DF, .(Variant,X), summarise, N = length(Y), mean=round(mean(Y),2), sd=round(sd(Y),2), se=round(sd(Y)/sqrt(length(Y)),2))

ord <- cdata[cdata$X == max(cdata$X),]
ord <- ord[order(ord$Variant, decreasing=T),]

pdf("out.pdf")

none <- element_blank()

bp <- ggplot(cdata, aes(x=X, y=mean, group=Variant)) + xlab("X label") + geom_line(aes(linetype=Variant)) + geom_point(aes(shape=Variant)) + ylab("Y Value") + labs(title = "mytitle") + scale_linetype_discrete(breaks = ord$Variant) + scale_shape_discrete(breaks = ord$Variant)

print(bp + theme(legend.justification=c(1,0), legend.position=c(1,0), legend.key.width=unit(3,"line"), legend.title=element_blank(), text = element_text(size=18))  + theme(panel.background = element_rect(fill='white', colour='black')) + theme(panel.grid.major = none, panel.grid.minor = none))

dev.off()
库(plyr)
图书馆(GG2)
需要(网格)

args如果您提供绘制图形所用的数据,这将非常有帮助。下面是一个如何处理我编写的一些数据的示例:

dat <- data.frame(x = c(1,2), y = rnorm(8), group = rep(c("bar", "baz", "bush", "foo"), each = 2))
ord <- dat[dat$x == max(dat$x),]
ord <- ord[order(ord$y, decreasing=T),]
ggplot(dat, aes(x, y)) + geom_point(aes(shape = group)) + geom_line(aes(group = group)) +
  scale_shape_discrete(breaks = ord$group)

dat谢谢!我已经用数据更新了我的问题,这次还更新了你的
ord
scale\u shape\u discrete
代码。然而,我正在寻找一个曲线图,每个组有不同的线型和不同的点类型。我希望线条类型和点类型反映在图例中。正如我更新的问题中所示,我的尝试给我留下了两个传奇……事实上,在freenode上的#R上的更多问题之后,这个问题现在解决了。查看对我的问题的编辑。