[英]Legend ordering in ggplot2
我使用ggplot2
在R
创建了以下图表。 正如你所看到的,传奇中的顺序并不完全是它应该是:我想在“1年”之后“4年”。 我想知道如何实现这一目标。
源代码:
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())
它将名称更改为因子变量并默认使用字母顺序
采用
df$names <- factor(df$names, levels = c("1 year","4 years","15 years","25 years","40 years"))
您可以使用fct_inorder
包中的fct_inorder将names
向量转换为所需“1年,4年”等序列中的有序因子:
library(forcats)
names = fct_inorder(c(names1,names2,names3,names4,names5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.