1

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

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

更新 2:这正是我所希望的,感谢#R (bosie) irc.freenode 上的@thomas-kern。诀窍是同时添加两者,即

 scale_linetype_discrete(breaks = ord$Variant) + scale_shape_discrete(breaks = ord$Variant)

这是我的R:

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

这正是我所追求的:

在此处输入图像描述

4

1 回答 1

3

如果你提供你的绘图所用的数据,它真的很有帮助。这是一个如何处理我编写的一些数据的示例:

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)

在此处输入图像描述

于 2013-11-15T00:45:37.317 回答