ggplot2中的图例排序 [英] Legend ordering in ggplot2

查看:216
本文介绍了ggplot2中的图例排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ggplot2R中创建了以下图形.如您所见,图例中的顺序并不完全应该是这样:我希望"1年"之后是"4年".我想知道如何实现这一目标.

I created the following graph in R using ggplot2. As you can see, the order in the legend is not exactly what it should be: I would like to have "4 years" coming after "1 year". I was wondering how this can be achieved.

源代码:

require("ggplot2")
require("scales")

# I have 5 data files containing two columns (x and y values)

d1 = read.table("1yr.txt")$V2
d2 = read.table("4yr.txt")$V2
d3 = read.table("15yr.txt")$V2
d4 = read.table("25yr.txt")$V2
d5 = read.table("40yr.txt")$V2
rank1 = read.table("1yr.txt")$V1
rank2 = read.table("4yr.txt")$V1
rank3 = read.table("15yr.txt")$V1
rank4 = read.table("25yr.txt")$V1
rank5 = read.table("40yr.txt")$V1
data = c(d1,d2,d3,d4,d5)
rank = c(rank1,rank2,rank3,rank4,rank5)

names1 = rep("1 year",length(d1))
names2 = rep("4 years",length(d2))
names3 = rep("15 years",length(d3))
names4 = rep("25 years",length(d4))
names5 = rep("40 years",length(d5))
names = c(names1,names2,names3,names4,names5)

df = data.frame(rank,data,names)

ggplot(df, aes(x=rank, y=data, group=names)) +
    geom_line(aes(color=names)) + 
    geom_point(shape=21, size=2.25, fill="white", aes(color=names)) +
    scale_y_continuous(limits = c(0.8e-2,2e2),trans = log10_trans(),
        breaks = trans_breaks("log10", function(x) 10^x),
        labels = trans_format("log10",math_format(10^.x))) +
    theme_bw() + scale_x_continuous() +
    labs(x="species rank",y="relative species abundance",color=NULL) +
    theme(panel.grid.minor = element_line(colour="gray95",size=0.01),
        legend.justification = c(0.95, 0.95), legend.position = c(0.95, 0.95),
        legend.background = element_rect(colour="black"),
        axis.ticks = element_blank(), axis.text.x = element_blank())

推荐答案

默认将名称更改为因子变量并默认使用字母顺序

It's changing names into a factor variable and using alphabetical order by default

使用

df$names <- factor(df$names, levels = c("1 year","4 years","15 years","25 years","40 years"))

这篇关于ggplot2中的图例排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆