Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

r - Legend ordering in ggplot2

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.

enter image description here

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())
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

use

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...