[英]How to adjust the ordering of labels in the default legend in ggplot2 so that it corresponds to the order in the data
我正在ggplot2中绘制一个森林图,并且在图例中符合数据集中标签顺序的标签排序方面存在问题。 这是我的代码如下。
d<-data.frame(x=c("Co-K(W) N=720", "IH-K(W) N=67", "IF-K(W) N=198", "CO-K(B)N=78", "IH-K(B) N=13", "CO=A(W) N=874","D-Sco Ad(W) N=346","DR-Ad (W) N=892","CE_A(W) N=274","CO-Ad(B) N=66","D-So Ad(B) N=215","DR-Ad(B) N=123","CE-Ad(B) N=79"),
y = rnorm(13, 0, 0.1))
d <- transform(d, ylo = y-1/13, yhi=y+1/13)
d$x <- factor(d$x, levels=rev(d$x)) # reverse ordering
credplot.gg <- function(d){
# d is a data frame with 4 columns
# d$x gives variable names
# d$y gives center point
# d$ylo gives lower limits
# d$yhi gives upper limits
require(ggplot2)
p <- ggplot(d, aes(x=x, y=y, ymin=ylo, ymax=yhi,group=x,colour=x,)) +
geom_pointrange(size=1) +
theme_bw() +
scale_color_discrete(name="Sample") +
coord_flip() +
theme(legend.key=element_rect(fill='cornsilk2')) +
guides(colour = guide_legend(override.aes = list(size=0.5))) +
geom_hline(aes(x=0), colour = 'red', lty=2) +
xlab('Cohort') + ylab('CI') + ggtitle('Forest Plot')
return(p)
}
credplot.gg(d)
这就是我得到的。 如您所见,y轴上的标签与数据中的标签匹配。 但是,它与图例中的顺序不同。 我不知道如何纠正这个问题。 这是我第一次在ggplot2中创建一个情节。 任何反馈都非常感谢。谢谢你们
不错的情节,尤其是第一个ggplot
! 我没有测试过,但我认为您需要的是在您的colour
的guide_legend
添加reverse=TRUE
(在Cookbook for R中找到 )。
如果我要再发一条评论,我会说按字母顺序排序你的垂直系数通常会使字母顺序不是特别有意义时比较容易。 (虽然你的alpha命令可能有意义。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.