Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7754207
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T12:15:00+00:00 2026-06-01T12:15:00+00:00

I am plotting line charts showing the change in price over time for multiple

  • 0

I am plotting line charts showing the change in price over time for multiple instruments, using ggplot2. I have succeeded in getting multiple lines on the plot and adding values showing the most recent change in price. What I want to do (and have not yet achieved) is to reorder the legend key so that the price series that has risen the most is at the top of the legend, followed by the key of the price series that rose second-most and so on.

In the plot below, the legend shows the key in alphabetical order. What I would like it to do is to show the legend key entries in the order DDD, AAA, CCC then BBB, which is the order of performance as of the most recent date. How can I do this?

ggplo2 chart showing legend order

Minimal-ish code follows.

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)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T12:15:01+00:00Added an answer on June 1, 2026 at 12:15 pm

    Try this:

    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

    I melted your full data set to save you several lines for plotting code. The key, as usual, is to make sure the variable is an ordered factor.

    To address the issue that arose in the comments, you can pass whatever labels you like to appear in the legend itself, as long as you get the order correct:

    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

    Note: Since version 0.9.2 opts has been replaced by theme, e.g.:

    + theme(axis.title.y = element_blank())
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm plotting a group of curves, using facet in ggplot2. I'd like to have
When plotting multiple data series using both line specification ( X , Y ,
I am looking for good plotting library (line, pie, column charts) which allows to
I'm plotting some data using geom_smooth and looking for a way to change the
I have a numpy array of ints representing time periods, which I'm currently plotting
I have been unable to find a simple analog for plotting a line graph
Is there a good command-line UNIX charting / graphing / plotting tool out there?
I am doing practice with JavaFX 2.0 by plotting a XYChart with 2 line
When plotting on a figure in MATLAB, I have noticed that parts of the
I am plotting a financial candlestick chart using this MATLAB function: http://www.mathworks.com/help/toolbox/finance/candlefts.html How do

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.