R:如何在 ggplot2 线图中重新排序图例键以匹配每个系列中的最终值?

标签 r ggplot2

我正在使用 ggplot2 绘制折线图,​​显示多种工具的价格随时间的变化。我已经成功地在图中获得了多条线,并添加了显示最近价格变化的值。我想要做的(并且尚未实现)是重新排序图例键,以便上涨最多的价格系列位于图例的顶部,其次是上涨第二大的价格系列的键,然后很快。

在下图中,图例按字母顺序显示了键。我希望它做的是按照 DDD、AAA、CCC 和 BBB 的顺序显示图例键条目,这是截至最近日期的性能顺序。我怎样才能做到这一点?

ggplo2 chart showing legend order

最小的代码如下。

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)

最佳答案

尝试这个:

mydf <- melt(mydf,id.var = 1)
mydf$variable <- factor(mydf$variable,levels = rev(myvals$variable[order(myvals$value)]),ordered = TRUE)

# plot multiple lines
p <- ggplot(data = mydf) +
    geom_line(aes(x = mydate,y = value,colour = variable,group = variable),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)

enter image description here

我融化了你的完整数据集,为你节省了几行代码来绘制代码。像往常一样,关键是确保变量是有序因子。

为了解决评论中出现的问题,您可以传递您喜欢出现在图例本身中的任何标签,只要您的顺序正确即可:
ggplot(data = mydf) +
    geom_line(aes(x = mydate,y = value,colour = variable,group = variable),size = 1) +
    scale_colour_manual("", values = c("aaa" = "red", "bbb" = "black", "ccc" = "blue", "ddd" = "green"),labels = c('Company D','Company A','Company C','Company B')) +
    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()

enter image description here

备注 : 从 0.9.2 版开始 optsreplaced来自 theme ,例如:
+ theme(axis.title.y = element_blank())

关于R:如何在 ggplot2 线图中重新排序图例键以匹配每个系列中的最终值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10074483/

相关文章:

R:错误:在 dplyr 中使用 unnest 时长度不兼容

r - 如何在串扰复选框过滤器旁边显示匹配条目的数量?

r - 在 ggplot 中的何处以及如何应用过滤器

r - 聚类图。添加簇号: Function fviz_cluster (factoextra)

perl - 如何计算 Perl 中给定正态分布的点的概率?

R使用封装地球球体计算地球上两点之间的距离

r - 在R中绘制简单的中介图

r - 如何在 Shiny 中自动显示 "right-size"ggplot?

r - 在 R googleVis sankey 图表中分配节点和链接颜色

r - 条形图 (ggplot2) 中的单个条形图错位