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.
Source code:
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())
You could use
fct_inorder
from the forcats package to turn thenames
vector into an ordered factor in your desired "1 year, 4 years", etc sequence:It's changing names into a factor variable and using alphabetical order by default
use