我正在使用ggplot2制作多种工具随时间价格变化的折线图。我已成功在图表上绘制了多条线,并添加了显示最近价格变化的值。我想做的是(但尚未实现)重新排序图例以使涨幅最大的价格系列位于图例的顶部,其次是第二大的价格系列,依此类推。
在下面的图中,图例按字母顺序显示标识。我希望它能够按照DDD,AAA,CCC然后BBB的性能顺序显示图例项,这是截至最近日期的顺序。我该如何做到这一点?
以下是类似代码的最小代码。
在下面的图中,图例按字母顺序显示标识。我希望它能够按照DDD,AAA,CCC然后BBB的性能顺序显示图例项,这是截至最近日期的顺序。我该如何做到这一点?
以下是类似代码的最小代码。
require(ggplot2)
require(scales)
require(gridExtra)
require(lubridate)
require(reshape)
# create fake price data
set.seed(123)
monthsback <- 15
date <- as.Date(paste(year(now()), month(now()),"1", sep="-")) - months(monthsback)
mydf <- data.frame(mydate = seq(as.Date(date), by = "month", length.out = monthsback),
aaa = runif(monthsback, min = 600, max = 800),
bbb = runif(monthsback, min = 100, max = 200),
ccc = runif(monthsback, min = 1400, max = 2000),
ddd = runif(monthsback, min = 50, max = 120))
# function to calculate change
change_from_start <- function(x) {
(x - x[1]) / x[1]
}
# for appropriate columns (i.e. not date), replace fake price data with change in price
mydf[, 2:5] <- lapply(mydf[, 2:5], function(myparam){change_from_start(myparam)})
# get most recent values and reshape
myvals <- mydf[mydf$mydate == mydf$mydate[nrow(mydf)],]
myvals <- melt(myvals, id = c('mydate'))
# plot multiple lines
p <- ggplot(data = mydf) +
geom_line( aes(x = mydate, y = aaa, colour = "AAA"), size = 1) +
geom_line( aes(x = mydate, y = bbb, colour = "BBB"), size = 1) +
geom_line( aes(x = mydate, y = ccc, colour = "CCC"), size = 1) +
geom_line( aes(x = mydate, y = ddd, colour = "DDD"), size = 1) +
scale_colour_manual("", values = c("AAA" = "red", "BBB" = "black", "CCC" = "blue", "DDD" = "green")) +
scale_y_continuous(label = percent_format()) +
geom_text(data = myvals, aes(x = mydate + 30, y = value, label = sprintf("%+1.1f%%", myvals$value * 100)), size = 4, colour = "grey50") +
opts(axis.title.y = theme_blank()) +
opts()
# and output
print(p)
scale_colour_manual("", values=c('aaa'="red", 'bbb'="blue", 'ccc'="black"), labels=c("Company A","Company B", "Company C"))
但是图例键的顺序以标签的顺序排序,而不是值的顺序,并且颜色也被错误地分配了。例如,'公司C'是-24.6%,应该是黑色的,但图例显示'公司B'是黑色的。所以我又回到原点了。 - SlowLearner