传奇在ggplot2中排序

时间:2017-05-01 17:17:41

标签: r plot ggplot2 legend

我使用Rggplot2中创建了以下图表。正如你所看到的,传奇中的顺序并不完全是它应该是:我希望有#4; 4年"过了一年" 1年"。我想知道如何实现这一目标。

enter image description here

源代码:

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

2 个答案:

答案 0 :(得分:4)

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

使用

a

答案 1 :(得分:3)

您可以使用forcats包中的fct_inordernames向量转换为所需“1年,4年”等序列中的有序因子:

library(forcats)
names = fct_inorder(c(names1,names2,names3,names4,names5))