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 7832005
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T11:59:10+00:00 2026-06-02T11:59:10+00:00

I want to colour the backgrounds of a ggplot2 facet plot depending on the

  • 0

I want to colour the backgrounds of a ggplot2 facet plot depending on the value given in a particular column. Using answers to previous questions I have already asked, I was able to piece what I needed together. @joran’s answer to this question was particularly useful as it illustrates the technique of creating a separate data frame to pass to ggplot.

This all works nicely enough, giving the output shown in the following image:
facets coloured by region

Here is the code I used to generate the above plot:

# User-defined variables go here

list_of_names <- c('aa','bb','cc','dd','ee','ff')
list_of_regions <- c('europe','north america','europe','asia','asia','japan')

# Libraries

require(ggplot2)
require(reshape)

# Create random data with meaningless column names
set.seed(123)
myrows <- 30
mydf <- data.frame(date = seq(as.Date('2012-01-01'), by = "day", length.out = myrows),
                   aa = runif(myrows, min=1, max=2),
                   bb = runif(myrows, min=1, max=2),
                   cc = runif(myrows, min=1, max=2),
                   dd = runif(myrows, min=1, max=2),
                   ee = runif(myrows, min=1, max=2),
                   ff = runif(myrows, min=1, max=2))

# Transform data frame from wide to long

mydf <- melt(mydf, id = c('date'))
mydf$region <- as.character("unassigned")

# Assign regional label

for (ii in seq_along(mydf$date)) {
    for (jj in seq_along(list_of_names)) {
        if(as.character(mydf[ii,2]) == list_of_names[jj]) {mydf$region[ii] <- as.character(list_of_regions[jj])}
    }
}

# Create data frame to pass to ggplot for facet colours
mysubset <- unique(mydf[,c('variable','region')])
mysubset$value <- median(mydf$value) # a dummy value but one within the range used in the data frame
mysubset$date <- as.Date(mydf$date[1]) # a dummy date within the range used

# ... And plot
p1 <- ggplot(mydf, aes(y = value, x = date, group = variable)) +
    geom_rect(data = mysubset, aes(fill = region), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 0.3) +
    scale_fill_manual(values = c("japan" = "red", "north america" = "green", "asia" = "orange", "europe" = "blue")) +
    geom_line() +
    facet_wrap( ~ variable, ncol = 2)

print (p1)

The real-world script towards which I am working is intended to be used for many different groups containing many different data series, so this script will be duplicated many times, with only the variables changing.

This makes it important to have the user-defined elements clearly accessible for editing, which is why the list_of_names and list_of_regions variables are put right at the start of the file. (Of course, it would be better not to need to change the script at all but rather define these lists as external files or pass them to the script as arguments.) I tried to generalise the solution by using those two for loops to assign the regions. I did fiddle around for a while trying to get a more R-centric solution using apply functions but couldn’t get it to work so I gave up and stuck with what I knew.

However, in my code as it stands the scale_fill_manual call needs to be explicitly passed variables to define fill colours, such as 'europe' = 'blue'. These variables will vary depending on the data I am processing, so with the script in its current form, I will need to manually edit the ggplot part of the script for each group of data series. I know that would be be time-consuming and I strongly suspect it would also be very prone to errors.

Q. Ideally I would like to be able to programmatically extract and define the required values for the scale_fill_manual call from a previously declared list of values (in this case from list_of_regions) matched to a previously declared list of colours, but I can’t think of a way to achieve this. Do you have any ideas?

  • 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-02T11:59:16+00:00Added an answer on June 2, 2026 at 11:59 am

    Does this help?

    cols <- rainbow(nrow(mtcars))
    mtcars$car <- rownames(mtcars)
    
    ggplot(mtcars, aes(mpg, disp, colour = car)) + geom_point() +
      scale_colour_manual(limits = mtcars$car, values = cols) +
      guides(colour = guide_legend(ncol = 3))
    

    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In XCode 4.2, I want to set a view's background colour to a particular
I'm using qplot to plot a function and I want to position the legend
I want to set the background color of a label using HSV instead of
I want to copy the background-color value and paste it in within the <strong>
I want to change the background colour of the rectangle in the IsMouseOver trigger,
I want to change the background colour of a cell inside UITableView from default
I want a way to set default settings like, background colour, size etc. for
I want the background colour of my tab item's header to change when it
I'm using the jQuery Cupertino theme and want to use the icons from that
In the following code, I want the background colour of the main GTK_WINDOW_TOPLEVEL to

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.